在angular流星中使用$push操作符更新mongodb

updating mongodb using $push operator in angular-meteor

本文关键字:push 操作符 更新 mongodb angular 流星      更新时间:2023-09-26

我正在尝试将数组从一个集合推送到另一个集合。这是我在服务器js 中使用的代码

    updateSettings: function(generalValue) {
     let userId = Meteor.userId();
       let settingsDetails = GeneralSettings.findOne({
   "_id": generalValue
 });
            Meteor.users.update({
     _id: userId
   }, {
     $push: {
       "settings._id": generalValue,
       "settings.name": settingsDetails.name,
       "settings.description": settingsDetails.description,
       "settings.tag": settingsDetails.tag,
        "settings.type": settingsDetails.type,
       "settings.status": settingsDetails.status
     }

   })
}

updateSettings是流星方法。GeneralSettings是第一个集合,user是第二个集合。我想把数组从GeneralSettings推送到users集合。当我尝试这个时,我得到的结果就像

 "settings" : {
    "_id" : [ 
        "GdfaHPoT5FXW78aw5", 
        "GdfaHPoT5FXW78awi"
    ],
    "name" : [ 
        "URL", 
        "TEXT" 
    ],
    "description" : [ 
        "https://docs.mongodb.org/manual/reference/method/db.collection.update/", 
        "this is a random text" 
    ],
    "tag" : [ 
        "This is a demo of an Url selected", 
        "demo for random text"
    ],
    "type" : [ 
        "url", 
        "text"
    ],
    "status" : [ 
        false, 
        false
    ]
}

但我想要的输出是

 "settings" : {
    "_id" : "GdfaHPoT5FXW78aw5",
    "name" :  "URL", 
    "description" :  
        "https://docs.mongodb.org/manual/reference/method/db.collection.update/", 
    "tag" :"This is a demo of an Url selected", 
    "type" :  "url",

    "status" :    false 

},

为了得到这个输出,在我的server.js中进行了哪些更改

这是一种"不希望"使用"点表示法"的情况。$push运算符期望和Object或基本上将向"左侧键"中命名的数组添加"右侧":

// Make your life easy and just update this object
settingDetails._id = generalValue;
// Then you are just "pushing" the whole thing into the "settings" array
Meteor.users.update(
  { _id: userId }, 
  { "$push": { "settings": settingDetails } }
)

当你在每个项目上使用"点符号"时,那就是要求为所提供的各个"键"中的"每个"创建"数组"。所以它只是"一个"数组键,以及作为参数添加的对象。