Mongodb findOneAndUpdate 函数正在插入新文档 [英] Mongodb findOneAndUpdate function is inserting new document

查看:69
本文介绍了Mongodb findOneAndUpdate 函数正在插入新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just need to update serviceActiveFlag status whenever i make an update api call.After an update api call,i can see a new document with empty vehicle array is created as shown below.

_id:59c76073c11d3929148f500f
vehicle:Array
_v:0

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

id field will override upon every put api call.

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

Can some one help me to resolve this issue?

架构

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);

控制器

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
                });
            }
        });

推荐答案

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

dbModel.findOneAndUpdate() of mongoose insert a new document only when your filter query(where claus) failed to find the existing document i.e there is no matching document exist in your collection. So mongoose will insert the new document to the collection. This works similar to upsert:true of update()

参考:有关 findOneAndUpdate 的官方文档

这篇关于Mongodb findOneAndUpdate 函数正在插入新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆