javascript - 在 angular-meteor 中使用 $push 运算符更新 mongodb

标签 javascript angularjs mongodb meteor mongodb-query

我正在尝试将数组从一个集合推送到另一个集合。 这是我在服务器 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 是 meteor 方法。 GeneralSettings 是第一个集合,user 是第二个集合。我想将数组从 GeneralSettings 推送到用户集合。当我尝试这个时,我得到的结果就像

 "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 or 基本上将“右侧”添加到“左侧键”中命名的数组中:

// 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 } }
)

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

关于javascript - 在 angular-meteor 中使用 $push 运算符更新 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36693027/

相关文章:

angularjs - 使用 $injector 与直接注入(inject)服务

javascript - meteor JS : RegisterHelper to display associated user information

Javascript html表格隐藏列

javascript - 如何 "alert"多维数组的某个元素

javascript - 如何在本地 JavaScript 变量中加载图像

javascript - Angularjs - 为什么我在使用 Google 自动完成地址表单时收到此 InvalidValue 错误

javascript - 对 Angular JS 中失败的日期应用过滤器

javascript - 使用 AngularJS 进行动态数据计算

node.js - 我收到 Mongoose 未定义的错误

mongodb - 有没有办法比较 MongoDB 查询中的两个字段