简体   繁体   English

如何将键/值对数组更新为猫鼬?

[英]How to update array of key/value pairs into a mongoose?

Background: I have an array of objects sent from Vue Axios.背景:我有一组从 Vue Axios 发送的对象。 These objects are key value pairs which is stored in the req.body.这些对象是存储在 req.body 中的键值对。

Req.body请求体

keyValue:  [{key:"some key", value:"some value"}, {key:"some key2", value:"some value2"}]

Note : I can expect to receive a req.body with a numerous amount objects withing the array.注意:我可以期望收到一个 req.body,其中包含数组中的大量对象。 I can not access the "key" and "value" in the objects without adding a [ ] or req.body.keyValue[0].如果不添加 [ ] 或 req.body.keyValue[0],我无法访问对象中的“键”和“值”。

How can I dynamically add each object's "key" and "value" into mongoose without having to explicitly call a specific object?如何在不必显式调用特定对象的情况下将每个对象的“键”和“值”动态添加到猫鼬中?

I am trying to do something like this: (failed attempt)我正在尝试做这样的事情:(失败的尝试)

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Schema = new Schema({
  Pair: [{
    Key: String,
    Value: Number
  }]
});

router.post("/",  (req, res) => {
 User.update({},
  {$push:
  {Pair:{
        Key: req.body.keyValue.key,
         Value: req.body.keyValue.value
       }
      }
    }, 
  (err,result)=>{
    if(err){
      console.log(err);
      res.status(400).send('Error')
    }else{
      res.status(200).send(result);
    }
  })
}

I hope I was able to explain well enough.我希望我能够解释得足够好。 Let me know if there is any confusions.让我知道是否有任何困惑。 Thanks!谢谢!

User Schema用户模式

userId: {
    type: String
},
password: {
    type: String
},
friends: [{
    userId: String,
    followSent: Boolean,
    followAccepted: Boolean,
    followbackSent: Boolean,
    followbackAccepted: Boolean,
    inchats: Boolean
}]

Update Code更新代码

userModel.updateOne({ userId: "MyId" , "friends.userId": "frndId"},{
$set: {
        'friends.$.followSent': true}},(err, docs) => {
                   
        })

The point here is that when your call req.body.keyValue.key and req.body.keyValue.value , they are in a javascript array req.body.keyValue[] .这里的要点是,当您调用req.body.keyValue.keyreq.body.keyValue.value时,它们位于 javascript 数组req.body.keyValue[]中。

Presuming that the req.body.keyValue will be always a valid array with the { key: '...', value: '...' } you can use the MongoDB $each operator to update your document.假设req.body.keyValue将始终是一个有效的数组,其中包含{ key: '...', value: '...' }您可以使用MongoDB $each 运算符来更新您的文档。

As:作为:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Schema = new Schema({
  Pair: [{
    key: String,
    value: Number
  }]
});

router.post("/",  (req, res) => {
  User.update(
    {},
    {
      $push: {
        Pair:{
          $each : req.body.keyValue
        }
      }
    }, 
    (err,result)=>{
      if(err){
        console.log(err);
        res.status(400).send('Error')
      }else{
        res.status(200).send(result);
      }
    }
  );
}

Now just be careful that req.body.keyValue has the right capitalization on each element, so you don't have *K*ey and/or *k*ey , that will not match your schema.现在请注意req.body.keyValue在每个元素上都有正确的大写字母,因此您没有*K*ey和/或*k*ey ,它们与您的架构不匹配。 =] =]

Edit编辑

Just to explain how the $each operator will work, see the following example:只是为了解释 $each 运算符将如何工作,请参见以下示例:

req.body = {
  keyValue : [
    { key : "key1", value : 1 },
    { key : "key2", value : 2 }
  ]
};

Document in User collection before the update:更新前User集合中的文档:

{
  _id : ObjectId(),
  Pair : [
    { key : "key_A", value : 99 }
  ]
}

After the .update() with the $each operator, the expected updated document:在带有$each运算符的.update()之后,预期的更新文档:

{
  _id : ObjectId(),
  Pair : [
    { key : "key_A", value : 99 },
    { key : "key1", value : 1 },
    { key : "key2", value : 2 }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM