如何使用一个请求更新数组对象的多个字段? [英] How to update multiple fields of an array object with one request?

查看:51
本文介绍了如何使用一个请求更新数组对象的多个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
   _id:xxxxstoreid
    store:{
        products:[
            {
                _id:xxxproductid,
                name:xxx,
                img:url,
            }
        ]
    }
}

由于我无法预测更新请求,参数可能只有名称或两者都有.

since i cannot predict the request for update, params may have just name or it may have both.

这是我的查询,它更新成功,但如果参数中不存在其他字段,它会删除其他字段.例如:

here is my query,it updates successfully but it removes other fields if they are not present in the params. eg:

var params={_id:xxid,name:'xxx',img:'xxx'}

var params={_id:xxid,name:'xxx'}

在这种情况下,如果 params 只是名称,它会删除 img 字段并更新.

in this case if params have just name it removes img field and updates.

User.update({'store.products._id':params._id},{$set:{"store.products":params}},callback);

推荐答案

您需要为 $set位置$ 运算符 更新两个匹配的键.

You need to supply the multiple keys to $set with the positional $ operator to update both matched keys.

我更喜欢现代 ES6 的对象操作方式:

I prefer the modern ES6 way of object manipulation:

let params = { "_id" : "xxxproductid", "name" : "xxx", "img" : "yyy" };

let update = [
  { 'store.products._id': params._id },
  { "$set": Object.keys(params).filter(k => k != '_id')
    .reduce((acc,curr) =>
      Object.assign(acc,{ [`store.products.$.${curr}`]: params[curr] }),
    { })
  }
];

User.update(...update,callback);

这会产生对 MongoDB 的调用,因为 ( with mongoose.set('debug', true) ) 打开,所以我们看到请求:

Which would produce the call to MongoDB as ( with mongoose.set('debug', true) ) turned on so we see the request:

猫鼬:users.update({ 'store.products._id': 'xxxproductid' }, { '$set': { 'store.products.$.name': 'xxx', 'store.products.$.img': 'yyy' } }, {})

Mongoose: users.update({ 'store.products._id': 'xxxproductid' }, { '$set': { 'store.products.$.name': 'xxx', 'store.products.$.img': 'yyy' } }, {})

基本上你输入 params 并提供 _id 作为查询"的第一个参数:

Where basically you take your input params and supply the _id as the first argument for the "query" :

  { 'store.products._id': params._id },

其余的通过 Object.keys 构成一个数组",我们可以使用 Array.filter() 然后传递给 Array.reduce 将这些键转换为 <代码>对象.

.reduce 内部() 我们称之为 Object.assign() 用给定的键合并"对象,以这种形式生成:

Inside the .reduce() we call Object.assign() which "merges" objects with the given keys, generated in this form:

  Object.assign(acc,{ [`store.products.$.${curr}`]: params[curr] }),

使用模板语法将当前"(curr)键"分配给新键名,再次使用 ES6 键赋值语法 []: 允许在对象字面量中使用变量名.

Using the template syntax to assign the "current" (curr) "key" into the new key name, again using the ES6 key assignment syntax []: which allows variable names in object literals.

生成的合并"对象被传递回以分配给根"对象,其中 $set 用于更新的键,因此生成的"键现在是

The resulting "merged" object is passed back to be assigned to the "root" object where $set is used for the key of the update, so the "generated" keys are now children of that.

我使用一个数组作为参数纯粹是为了调试目的,但这也允许在实际 .update() 上使用spread"... 更清晰的语法> 运算符来分配参数:

I use an array for the arguments purely for debugging purposes, but then that also allows cleaner syntax on the actual .update() using the "spread" ... operator to assign the arguments:

User.update(...update,callback);

简洁明了,以及一些您应该学习的对象和数组操作的 JavaScript 技术.主要是因为 MongoDB 查询 DSL 基本上是对象"和数组".所以要学会操纵它们.

Clean and simple, and some JavaScript techniques that you should learn for object and array manipulation. Mostly since the MongoDB query DSL is basically "Objects" and "Arrays". So learn to manipulate them.

这篇关于如何使用一个请求更新数组对象的多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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