如何用猫鼬更新

How to update with mongoose

我有这个记录

{
    "_id" : ObjectId("5dfdff479ad032cbbc673507"),
    "selection" : [ 
        {
            "highlights" : "test",
            "comment" : "CHANGE THIS",
            "el" : "body:nth-child(2)>div:nth-child(2)#root>div.App>p:nth-child(1)"
        }, 
        {
            "highlights" : "Barrett’s lyrical prose opens with a clever and tender solution",
            "comment" : "",
            "el" : "body:nth-child(2)>div:nth-child(2)#root>div.App>p:nth-child(2)"
        }
    ],
    "category" : [],
    "status" : "",
    "url" : "http://localhost:3000/theone",
    "title" : "React App test",
    "__v" : 4
}

我想更新 comment。我尝试使用 updatefindOneAndUpdate 但没有任何效果。这是我的尝试

WebHighlight.findOneAndUpdate(
  {
    _id: req.params.highlight,
    "selection.highlights": "test"
  },
  { "selection.$.comment": "yourValue" }
);

那个req.params.highlight是id(我什至硬编码了)

我也试过这个

WebHighlight.findById(req.params.highlight, (err, book) => {
  var test = [...book.selection];
  test[0].comment = "somethibf"
  book.save();
  res.json(book);
});

没有任何效果。

这是模型

const webhighlightsModel = new Schema({
  selection: { type: Array, default: "" },
  category: { type: Array, default: [] },
  title: { type: String },
  url: { type: String },
  status: { type: String, default: "" }
});

您应该使用 $set 运算符来更新现有值:

WebHighlight.findOneAndUpdate(
  {
    _id: req.params.highlight,
    "selection.highlights": "test"
  },
  { '$set': { "selection.$.comment": "yourValue" } }
);

实际上您的代码似乎可以工作,但是 findOneAndUpdate returns 旧文档 如果您不提供 {new: true} 选项。

我认为由于这个原因,您认为更新没有成功,但是如果您检查 collection,您会看到更新。

WebHighlight.findOneAndUpdate(
  {
    _id: req.params.highlight,
    "selection.highlights": "test"
  },
  { "selection.$.comment": "yourValue" },
  { new: true }
)
  .then(doc => res.send(doc))
  .catch(err => res.status(500).send(err));

另外我认为如果选择有这样的子模式会更好:

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
  selection: [
    new mongoose.Schema({
      highlights: String,
      comment: String,
      el: String
    })
  ],
  category: { type: Array, default: [] },
  title: { type: String },
  url: { type: String },
  status: { type: String, default: "" }
});

module.exports = mongoose.model("WebHighlight", schema);

所以每个选择都会有一个 _id 字段,最好用这个 _id 更新。