[英]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.