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);
    });
noobie
  • 2,427
  • 5
  • 41
  • 66
  • Look at the "options" in the documentation for "new". – Blakes Seven Jul 13 '15 at 07:57
  • possible duplicate of [how to get the return value of findAndModify func in MongoDB with mongoose?](http://stackoverflow.com/questions/9773684/how-to-get-the-return-value-of-findandmodify-func-in-mongodb-with-mongoose) – Blakes Seven Jul 13 '15 at 07:59

1 Answers1

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.

real_ate
  • 10,861
  • 3
  • 27
  • 48
  • 1
    I actuallly thought I had this field defined in my schema. When I double checked, I noticed it was not there at all. Thanks – noobie Jul 13 '15 at 22:08
  • 1
    Wow what a simple but dumb mistake, thanks anyway! – Jarrett Dec 25 '20 at 10:44
  • @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? – Kasir Barati Jan 31 '22 at 09:12
  • 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 – real_ate Feb 01 '22 at 10:24