简体   繁体   中英

findOneAndUpdate is not working in mongodb/nodejs

I am trying to update a Record in mongodb using nodejs but it isn't working I am getting data on the other side and everything seems to be working but it just won't update the record

My server Side code is

 console.log('here',req.params.userId )
  User.findOneAndUpdate({ _id: req.params.userId }, {$set:req.body}, { new: true }, function (err, users) {
    if (err)
        res.send(req.params.userId);
res.json(users);
});

It returns a null value I don't know why. Any Help would be Appreciated.

This is because Mongo's ObjectId() came rendered as string in req.body:

do this:


console.log('here',req.params.userId )

User.findOneAndUpdate({ _id: new ObjectId(req.params.userId) }, {$set:req.body}, { new: true }, function (err, users) {
    if (err) res.send(req.params.userId);

    res.json(users);
});

You can require ObjectId from bson package as I work with TypeScript the import I use is import { ObjectId } from 'bson'; in pure javascript should be import ObjectId = require('bson');

You can do it like that:

User.findOneAndUpdate(
  { _id: new ObjectId(req.params.userId) },
  ...req.body,
  { new: true }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM