![](/img/trans.png)
[英]Mongodb/Mongoose: How to properly implement findOneAndUpdate on an express route
[英]JavaScript - Express - MongoDb - Mongoose findOneAndUpdate is returning undefined
因此,我正在嘗試更新mongodb數據庫中的項目,但該項目無法正常工作,並且將error關鍵字設置為undefined。 我可能做錯了什么,但這是更新功能:
router.post("/file/:id/edit", (req, res) => {
var id = req.params.id;
File.findOneAndUpdate( {"_id": id} , req.body, (err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
調用它的函數:
export function updateFile(file) {
var objIdToUpdate = file["id"];
var myUpdate = axios.post("http://localhost:3001/api/file/:" + objIdToUpdate + "/edit", {
title: file.title,
author: file.author,
dateCreated: file.dateC,
dateModified: file.dateModified,
size: file.size,
type: file.type,
tags: file.tags
});
return myUpdate;
}
我的架構:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const FileSchema = new Schema(
{
title: String,
author: String,
dateCreated: String,
dateModified: String,
size: String,
type: String,
tags: []
},
{ timestamps: true }
);
module.exports = mongoose.model("File", FileSchema, "files");
當我嘗試打印“ err”關鍵字時,它只是未定義。 為什么這對修改數據庫中的值不起作用,出了什么問題?
在findOneAndUpdate的回調函數中,err中始終會有一個值,如果您使用then並捕獲如下承諾,則更好:
File.findOneAndUpdate({ "_id": req.params.id}, { req.body },{returnNewDocument: true})
.then((resp) => { res.send(resp) })
.catch((err) => { res.send(err) });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.