简体   繁体   English

JavaScript-Express-MongoDb-Mongoose findOneAndUpdate返回未定义

[英]JavaScript - Express - MongoDb - Mongoose findOneAndUpdate is returning undefined

So I'm trying to update an item within my mongodb database but it's not working and the error keyword is being set to undefined. 因此,我正在尝试更新mongodb数据库中的项目,但该项目无法正常工作,并且将error关键字设置为undefined。 I'm probably doing something very wrong but here's the update function: 我可能做错了什么,但这是更新功能:

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 });
  });
});

The function that calls it: 调用它的函数:

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;
}

My schema: 我的架构:

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");

When I try to print the "err" keyword it's simply undefined. 当我尝试打印“ err”关键字时,它只是未定义。 Why is this not working to modify values in my database, what's gone wrong? 为什么这对修改数据库中的值不起作用,出了什么问题?

In your callback function of findOneAndUpdate, err always have a value in it, its better if you use the then and catch with promises like this: 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM