首页 > 解决方案 > findByIdAndUpdate 不更新文档

问题描述

我正在尝试使用 findByIdAndUpdate 将字段更新到文档中。我尝试更新的字段在条形模型中定义。而且我还可以保证req.body.bookId有一个有效的身份证。

这是我的请求的样子,

app.patch("/foo", async (req, res) => {
    try {
        await validateId(req.body.bookId);

        let doc = await Bar.findByIdAndUpdate(
            req.body.bookId,
            { DateT: Date.now() },
            { new: true }
        );

        res.send(doc);
    } catch (err) {
        console.log(err);
    }
});

条形图,

const mongoose = require("mongoose");

const barSchema = mongoose.Schema({
    bookId: {
        type: String,
        unique: true,
    },
    DateT: {
        type: Date,
        default: null,
    },
});

module.exports = mongoose.model("Bar", barSchema);

标签: mongodbexpressmongoose

解决方案


使用updateOne,当你使用时async不要.then()使用try/catch

测试它:


app.patch("/foo", async (req, res) => {
  try {
    let doc = await Bar.updateOne(
      { bookId : req.body.bookId },
      { DateT: Date.now() },
      { new: true }
    );
    res.send(doc);
  } catch (error) {
    console.log(error);
  }
});

推荐阅读