【问题标题】:JavaScript - Express - MongoDb - Mongoose findOneAndUpdate is returning undefinedJavaScript - Express - MongoDb - Mongoose findOneAndUpdate 返回未定义
【发布时间】:2019-07-12 09:17:07
【问题描述】:

所以我正在尝试更新我的 mongodb 数据库中的一个项目,但它不起作用,并且错误关键字被设置为未定义。我可能做错了什么,但这里是更新功能:

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”关键字时,它只是未定义。为什么这不能修改我的数据库中的值,出了什么问题?

【问题讨论】:

    标签: javascript mongodb express schema


    【解决方案1】:

    在你的 findOneAndUpdate 回调函数中,err 总是有一个值,如果你使用 then 和 catch 像这样的 Promise 会更好:

    File.findOneAndUpdate({ "_id":  req.params.id}, { req.body },{returnNewDocument: true})
        .then((resp) => { res.send(resp) })
        .catch((err) => { res.send(err) });
    

    【讨论】:

    • 当我尝试这样做时,我收到一条错误消息,告诉我“传入的参数必须是 12 个字节的单个字符串或 24 个十六进制字符的字符串”。我应该使用不同的功能吗?
    • 我更新了我的回复,因为强制转换并不是真正必要的,而且您使用的 id 可能无效,您能给我们您尝试访问的 url 吗?
    • 好吧,我不完全确定为什么,但这似乎有效。非常感谢!
    猜你喜欢
    • 2012-11-29
    • 1970-01-01
    • 2019-07-10
    • 2019-03-25
    • 1970-01-01
    • 2019-10-14
    • 2016-01-26
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多