![](/img/trans.png)
[英]Find user in mongo, with mongoose, and return the result to a JSON
[英]How to find then Update a user record Mongo/Mongoose
運行此代碼時,我得到 user.update is not a function 。 我一直無法在網上找到好的 mongo/mongoose 文檔。
//Add Event
app.post("/addEvent", (req, res, next) => {
const event = req.body.event;
console.log(req.user.id);
console.log(event);
User.find({ _id: req.user.id }, function(err, user) {
if (err) {
console.log(err);
return next(err);
}
if (user) {
user.update(
{
_id: req.user.id
},
{
$push: { events: event }
}
);
}
res.end();
});
});
};```
試試這個,我想它可能對你有幫助。
app.post("/addEvent", (req, res, next) => {
const event = req.body.event;
console.log(req.user.id);
console.log(event);
User.findById({ req.user.id }, async function(err, user) {
if (err) {
console.log(err);
return next(err);
}
if (user) {
User.updateOne(
{
_id: req.user.id
},
{
$push: { events: event }
}
);
}
res.end();
});
});
};
我還建議您在您的情況下使用帶有必要選項的findByIdAndUpdate或findOneAndUpdate 。 或者findOne
而不是find
因為 find 返回的是文檔的 [array],而不是一個文檔,所以如果您將像這樣使用async/await
:
const docs = Users.find(query,callback)
他們訪問必要文檔的唯一方法是docs[n]
,其中n
是結果數組中的文檔數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.