【问题标题】:I can't add elements in my schema ($addToSet)我无法在架构中添加元素 ($addToSet)
【发布时间】:2022-01-15 09:47:12
【问题描述】:

我有这样的计划。使用命令时,我希望在那里添加新项目

const userSchema = new mongoose.Schema({
    _id: {                      //user id
        type: String,
        required: true,
    },
    books: [{                  //book that user uses    
            _id: {               //book id
                type: Number,
                required: true,
            },
            lessons: [{          //lessons of the book with progress
                type: String,
                required: true,
            }],
    }],
})

我正在尝试以这种方式添加它们。

await userSchema.findByIdAndUpdate(author.id, { $addToSet: { books: {_id: bookid, lessons: progress} } })

bookid - int 值加一。 progress - 字符串数组

但是只有一组课程被写入基础,没有 id。 当我只添加 id 时,不会添加 id,而是添加一系列课程。 我已经花了几个小时,我不明白为什么它不想将所有东西都添加到数组中。请帮忙。

【问题讨论】:

    标签: node.js mongodb mongoose discord.js mongoose-schema


    【解决方案1】:

    尝试使用$push 运算符:

    await userSchema.findByIdAndUpdate(author.id, {
      $push: { 
        books: {
          _id: bookid,
          lessons: progress
        }
      } 
    })
    
    

    【讨论】:

    • 我试过了,但它仍然输入没有id,只是出于某种原因添加了一个数组。
    • 在查询前尝试console.log(bookid)。也许它是空的或未定义的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    相关资源
    最近更新 更多