仅当文档存在时更新文档,否则不要在MongoDB中插入文档
如果找不到匹配的数据,我不想在MongoDB中插入新文档 findOneAndUpdate()似乎不起作用。它抛出一个运行时错误,表示“无法读取null的属性'firstField'” 我的模式如下所示:仅当文档存在时更新文档,否则不要在MongoDB中插入文档,mongodb,mongoose,Mongodb,Mongoose,如果找不到匹配的数据,我不想在MongoDB中插入新文档 findOneAndUpdate()似乎不起作用。它抛出一个运行时错误,表示“无法读取null的属性'firstField'” 我的模式如下所示: const mongoose = require("mongoose"); const TestSchema = mongoose.Schema( { firstField: { type: String, required: true, uni
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");
});
您可以使用filter和update,然后使用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);
var collection=db.GetCollection(“集合名称”);
var filter=Builders.filter.Eq(“要筛选的字段”,“字段的值”);
var update=Builders.update.Set(“要更新的字段”,“值”)
collection.UpdateOne(过滤器,更新);
任何关于确定正确方法的帮助都非常有用。谢谢请在您的问题中发布示例文档和您如何保存它的代码。(您可以使用文章底部的edit
链接/按钮进行编辑)。