Using mongoose to add new field to existing document in mongodb through update method

后端 未结 3 1583
南笙
南笙 2021-02-20 07:45

I\'m trying to update a mongodb document with mongoose in node.js

When the field exists, the update works, but if the field does not exist, the update will not work.

3条回答
  •  别那么骄傲
    2021-02-20 08:41

    According to new scenario always use {upsert:true}.

    upsert - if set to true and no record matched to the query, replacement object is inserted as a new record.

       user.updateOne(
                     { email: req.body.email },
                     { $set: { name: 'Aaakash'}},{upsert:true}).then((result, err) => {
                        return res.status(200).json({ data: result, message:"Value Updated" });
                    })
    

提交回复
热议问题