[英]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我正在尝试使用 nodejs 更新 mongodb 中的记录,但它不起作用我正在另一端获取数据,一切似乎都在工作,但它不会更新记录
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.它返回一个 null 值,我不知道为什么。 Any Help would be Appreciated.任何帮助,将不胜感激。
This is because Mongo's ObjectId() came rendered as string in req.body:这是因为 Mongo 的 ObjectId() 在 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';
您可以要求来自 bson package 的 ObjectId,因为我使用 TypeScript 我使用的导入是import { ObjectId } from 'bson';
in pure javascript should be import ObjectId = require('bson');
在纯 javascript 中应该是import ObjectId = require('bson');
You can do it like that:你可以这样做:
User.findOneAndUpdate(
{ _id: new ObjectId(req.params.userId) },
...req.body,
{ new: true }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.