1

I couldn't push the data in the nested query

I couldn't understand what I missed in my code (I am new in mongodb just experimenting )

My target is adding 'post' in posts

const Schema = mongoose.Schema;
const UserDetail = new Schema({
    username: String,
    password: String,
    firstname: String,
    lastname: String,
    email: String,
    posts: {
        post:{
            title: String,
            article: String,
            comments: {}
        }
    }
});
const User = mongoose.model('userInfo', UserDetail, 'userInfo');

module.exports = User;

Here my updating code

User.findOneAndUpdate({_id: req.user._id},{ $push: {"posts": { "post" : { "article": req.body.description }} }     });

Thank you in advance

1 Answer 1

1

$push is used to append a specified value to an array. If the field is absent in the document to update, it adds the array field with the value as its element but if the field is not an array, the operation will fail. In your case posts is an embedded document, not an array.

You can either update your schema to make posts an array as:

const Schema = mongoose.Schema;
const UserDetail = new Schema({
    username: String,
    password: String,
    firstname: String,
    lastname: String,
    email: String,
    posts: [
        {
            title: String,
            article: String,
            comments: []
        }
    ]
})

then do a push

User.findByIdAndUpdate(req.user,
   { "$push": { 
       "posts": { 
           "article": req.body.description  
       } 
   } }  
);

or use $set with the dot notation if using the existing schema. The operation with $set follows this example:

User.findByIdAndUpdate(req.user,
   { "set": { "posts.post.article": req.body.description  } } 
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.