首页 > 解决方案 > 如何使用 mongoose 仅​​更新 mongodb 中传递的值?

问题描述

我已经构建了一个 API,它使用 mongoose 更新 MongoDB 中的记录,但目前发生的情况是,如果我只传递邮递员4 field中的值JSON file并尝试更新,那么所有值都更新为 null 值,除了我传入的 4 个字段JSON所以任何人都可以帮助我如何传递动态字段和值,这些字段和值仅更新传递的集合值而不是集合的所有字段。

传递 JSON :

{
    "preferance_id" : "60fe9ba1766d10d65c64083c",
    "is_active": true,
    "price_blur":true,
    "affiliate_commission":27,
    "language_code": "en"
 }

更新我在节点 js 中传递的调用

transaction.update(PreferencesMasterName,
                    { _id: new mongoose.Types.ObjectId(preferance_id) }, {
                        subscriptin_vat : subscriptin_vat,
                        popular_normal : popular_normal,
                        popular_crawled : popular_crawled,
                        price_blur : price_blur,
                        blur_rule : blur_rule,
                        affiliate_commission : affiliate_commission,
                        red_lock : red_lock,
                        automatic_dummy_price : automatic_dummy_price,
                        ...
                        is_active: is_active
                })

我想在这里传递动态字段和值而不是这个,因为由于这个,其他值被设置为null值。那么,任何人都可以知道如何做到这一点?

标签: node.jsmongodbmongoosemongodb-query

解决方案


你可以这样做:


const data = res.body; // should be an object that needs to updated

 transaction.update({_id: PreferanceMasterName._id}, data, {new: true }, ( error, obj ) => {
            if( error ) {
                console.error( JSON.stringify( error ) );
            }
            console.log( obj );
        });

在某些情况下new不起作用,您可以使用 : { returnOriginal: false }; 有关更多详细信息,您可以查看线程,有多种方法可以做到这一点。

请检查更新如何使用它。


推荐阅读