Search code examples
node.jsmongodbmongoosemongoose-schema

Pushing into Mongoose array is not updating the array


I have a User schema with a collections property that holds collection objects. These collection objects have a property called items that is an array of objects.

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

Using the code below, I tried creating and pushing a new Item Schema into the first collection object. I pass the _id of the collection object I want to update using the findById function. After finding the collection with my id, I simply just push a Item Schema into the collection object's items array. I get the res.status(200) yet my items array is never updated. Does anyone else have this issue? Thank you for you help.

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


Solution

  • You don´t perform any update operation on the Collection with the newly created Item document in the database.

    Add the created Item document by using the $addToSet operator (https://docs.mongodb.com/manual/reference/operator/update/addToSet/) to the items property in Collection (I would suggest by using mongoose findByIdAndUpdate method or updateOne method).

    It would be something like this using callbacks:

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

    If you have multiple Item documents which you need to insert into Collection, you can use $addToSet in combination with the $each operator (https://docs.mongodb.com/manual/reference/operator/update/each/).