【问题标题】:Pushing into Mongoose array is not updating the array推入 Mongoose 数组不会更新数组
【发布时间】:2020-12-12 13:25:57
【问题描述】:

我有一个包含集合对象的集合属性的用户模式。这些集合对象有一个名为 items 的属性,它是一个对象数组。

//User Schema
const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required : true,
    },
    password: {
        type: String,
        required: true
    },
    collections: [{type : mongoose.Schema.Types.ObjectId, ref: 'Collection'}]
}); 

//Collection Schema 
const CollectionSchema = new mongoose.Schema({
    items : [{type : mongoose.Schema.Types.ObjectId, ref: 'Item'}]
}); 

//Item Schema

const ItemSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
}); 

使用下面的代码,我尝试创建一个新的项目架构并将其推送到第一个集合对象中。我使用 findById 函数传递了要更新的集合对象的 _id。在找到带有我的 id 的集合后,我只需将 Item Schema 推送到集合对象的 items 数组中。我得到 res.status(200) 但我的 items 数组从未更新。还有其他人有这个问题吗?谢谢你的帮助。

userRouter.post('/addItem', passport.authenticate('jwt', {session: false}), (req, res) => {
    const item = new Item(req.body)

    item.save(err => {
        if(err)
            res.status(500).json({message: {msgBody: "Error has occured", msgError: true }});
        else {
            Collection.findById(req.body.search, function(err, coll){
                coll.items.push(item);
                req.user.save(err => {
                    if(err)
                        res.status(500).json(err)
                    else{
                        res.status(200).json(coll)
                    }
                })
            })
        }
    })
});

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    您不会使用数据库中新创建的 Item 文档对 Collection 执行任何更新操作。

    使用 $addToSet 运算符 (https://docs.mongodb.com/manual/reference/operator/update/addToSet/) 将创建的 Item 文档添加到 Collection 中的 items 属性(我建议使用 mongoose findByIdAndUpdate 方法或 updateOne 方法)。

    使用回调会是这样的:

    Collection.findByIdAndUpdate(req.body.search, { $addToSet: {items: item._id}}, callback);
    
    

    如果您有多个 Item 文档需要插入到 Collection 中,您可以将 $addToSet 与 $each 运算符 (https://docs.mongodb.com/manual/reference/operator/update/each/) 结合使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-17
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多