【问题标题】:How to Update only passed value in mongodb using mongoose?如何使用 mongoose 仅​​更新 mongodb 中传递的值?
【发布时间】:2021-10-02 08:46:08
【问题描述】:

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

通过 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.js mongodb mongoose mongodb-query


    【解决方案1】:

    你可以这样做:

    
    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 }; 有关更多详细信息,您可以查看this 线程,有多种方法可以做到这一点。

    请查看update如何使用。

    【讨论】:

    • 我厌倦了你的解决方案,但得到一个错误`Cast to ObjectId failed for value t(ype Object) at path \"_id\" for model \"preferences`。
    • 什么是PreferencesMasterName?我假设它是您正在为其更新值的文档的_id。
    • PreferenceMasterName 是 MongoDB 的集合名称。我收到了登录 ID 和登录电子邮件作为响应,我没有存储在数据库中
    • 第一个对象是查找查询,它必须正确才能运行更新查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2015-12-12
    • 2017-01-06
    • 1970-01-01
    • 2017-10-25
    • 2022-01-09
    相关资源
    最近更新 更多