推入Mongoose数组不会更新数组

问题描述

我有一个带有集合属性用户架构,该架构包含集合对象。这些集合对象具有称为项目的属性,该属性是对象的数组。

//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
}); 

使用下面的代码,我尝试创建一个新的Item Schema并将其推入第一个集合对象。我使用findById函数传递要更新的集合对象的_id。在找到具有我的ID的集合之后,我只需将项目模式推入集合对象的项目数组即可。我得到了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)
                    }
                })
            })
        }
    })
});

解决方法

对于数据库中新创建的Item文档,您不对集合执行任何更新操作。

使用$ 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/)结合使用。