![](/img/trans.png)
[英]MongoDb NodeJS driver findOneAndUpdate not working atomically
[英]findOneAndUpdate is not working in mongodb/nodejs
我正在尝试使用 nodejs 更新 mongodb 中的记录,但它不起作用我正在另一端获取数据,一切似乎都在工作,但它不会更新记录
我的服务器端代码是
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);
});
它返回一个 null 值,我不知道为什么。 任何帮助,将不胜感激。
这是因为 Mongo 的 ObjectId() 在 req.body 中呈现为字符串:
做这个:
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);
});
您可以要求来自 bson package 的 ObjectId,因为我使用 TypeScript 我使用的导入是import { ObjectId } from 'bson';
在纯 javascript 中应该是import ObjectId = require('bson');
你可以这样做:
User.findOneAndUpdate(
{ _id: new ObjectId(req.params.userId) },
...req.body,
{ new: true }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.