gpt4 book ai didi

javascript - Mongodb findOneAndUpdate 函数正在插入新文档

转载 作者:行者123 更新时间:2023-12-03 07:14:00 28 4
gpt4 key购买 nike

每当我进行更新 api 调用时,我只需要更新 serviceActiveFlag 状态。更新 api 调用后,我可以看到创建了一个包含空车辆数组的新文档,如下所示。

_id:59c76073c11d3929148f500f
vehicle:Array
_v:0

id 字段将在每次 put api 调用时覆盖。

有人可以帮我解决这个问题吗?

架构

var localTransportSchema = new Schema({

name: { type: String, required: false, trim: true },
contact: {
addressLine1: { type: String, required: false },
serviceActiveFlag: { type: String, required: false, enum: ['Y', 'N'] },
},
vehicle: [{
vehicleType:{ type: String, required: false, enum: ['sedan', 'hatchback', 'suv', 'mpv', 'luxury'] },
}]
});
module.exports.accomodationModel = mongoose.model(collection, localTransportSchema);

Controller

var updates = {
$set: {
"contact.addressLine1": req.body['addressLine1'],
"contact.serviceActiveFlag": req.body['serviceActiveFlag']
}
};

transportModel.findOneAndUpdate({ "name": req.body['providerName']},
updates, { returnOriginal: false, upsert: false }, function (err, doc) {
if (err) {
logger.error("Error while updating record : - " + err.message);
return res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " in transport details table"
});
} else if (doc === null) {
logger.error("Error while updating record in transport details : - unable to update database");
return res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " due to " + err.message
});
}
});

最佳答案

mongoose 的

dbModel.findOneAndUpdate() 仅在您的过滤器查询(where claus)未能找到现有文档时插入新文档,即您的集合中不存在匹配的文档。所以 mongoose 会将新文档插入到集合中。这类似于 update()

upsert:true

引用:Official docs about findOneAndUpdate

关于javascript - Mongodb findOneAndUpdate 函数正在插入新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46387861/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com