如果找不到匹配的数据,我不想在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");
});
答案 0 :(得分:0)
您可以使用筛选和更新,然后使用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);