如果仅存在则更新文档,否则不要在MongoDB中插入文档

如果找不到匹配的数据,我不想在MongoDB中插入新文档。

findOneAndUpdate()似乎不起作用。它将引发运行时错误,提示“无法读取null的属性'firstField'”

我的模式如下:

const mongoose = require("mongoose");
const TestSchema = mongoose.Schema(
  {
    firstField: {
      type: String,required: true,unique: true,sparse: true
    },secondField: {
      type: [String],required: true
    }
);

module.exports = mongoose.model("Test",TestSchema);

我的查询如下:

Test.findOneAndUpdate(
  {
    secondField: { $in: req.body.second }
  },{ $set: { firstField: req.body.first } },{ new: true },(err,test) => {
    if (err) {
      console.log("There are no matching first fields");
      console.log(err);
    }
    console.log("Field updated successfully");
});
ltye1113 回答:如果仅存在则更新文档,否则不要在MongoDB中插入文档

您可以使用筛选和更新,然后使用UpdateOne。例如。

var collection = db.GetCollection<BsonDocument>("Collection name");

var filter = Builders<BsonDocument>.Filter.Eq("the field you want to filter by","the value of the field");
var update = Builders<BsonDocument>.Update.Set("the field you want to update","value")
collection.UpdateOne(filter,update);
本文链接:https://www.f2er.com/3125917.html

大家都在问