7

I am trying to insert a new field 'description' with a findOneAndUpdate statement using Mongoose js. It is not working. The code works fine when the field already exists and updates it with the given value. According to the Mongodb documentation $set should create this field automatically if it does not exist.

Any ideas appreciated.

Course.findOneAndUpdate({'_id': CourseId},{$set:{'description':courseDescription}},function(err, course) {
        if (err)
            res.jsonp({response:'err'});

        res.jsonp(course);
    });
2

1 Answer 1

14

With mongoose you cannot set arbitrary fields, at least not in the way your trying to in your example.

You need to add the description to your Course Schema and then your code example will work.

Sign up to request clarification or add additional context in comments.

4 Comments

I actuallly thought I had this field defined in my schema. When I double checked, I noticed it was not there at all. Thanks
Wow what a simple but dumb mistake, thanks anyway!
@real_ate, @noobie @jarret I faced a very weird behavior from the mongoose. Even I defined the new fields in the schema and ModelName.findByIdAndUpdate(id, { $set: { desc: 'val' } }, { new: true, lean: true }) but it does not work. The generated mongodb query has no desc field. IDK what is wrong. Do you have any thought?
you should double-check your schema, the point of this answer is that if you don't have things updating then it's likely that your schema is missing something

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.