将值更新到数据库集合的数组中

时间:2014-03-22 00:43:44

标签: node.js mongodb sails.js

我正在使用Sails.js框架使用Node.js构建一个Web应用程序,我需要更新我的数据库集合(MongoDB)上的数组上的某些字段。

这是我的用户模型:

attributes: {

  name      : {
    type  : 'string'
  },

  encryptedPassword : {
    type  : 'string'
  },

  email: {
    type  : 'string',
    email : true
  },

  photos : {
    type: 'array'
  }

在照片阵列上,我添加了用户的照片信息,如图片网址,图片名称和所选的字段,这意味着用户是否选择了此图片。这是一个集合的例子:

"photos" : [ 
    {
        "id" : "94036c20b12711e3abdf9162d9e75321",
        "url" : "http://tmp.transloadit.com.s3.amazonaws.com/94036c20b12711e3abdf9162d9e75321.jpg",
        "selected" : false
    }, 
    {
        "id" : "9d5aa090b12711e3a4bb83478bef61eb",
        "url" : "http://tmp.transloadit.com.s3.amazonaws.com/9d5aa090b12711e3a4bb83478bef61eb.jpg",
        "selected" : false
    }
  ]

在视图中,我正在渲染这些照片,每张照片都有一个复选框输入,所以基本上这个想法是用户浏览所有照片并选择他/她想要的照片,并在表格获得后提交后,我会收到所选照片的​​数据,并将selected字段更新为true

这是我console.log(req.body)时的回复对象:

{
"photos-ids":[
    "94036c20b12711e3abdf9162d9e75321",
    "9d5aa090b12711e3a4bb83478bef61eb",
    "ad65d5e0b12711e38644f5b433a44603"
],
"user-id":"532c86a3f0fd88560792b3dd"
}

最后,基本上我需要做的是更新 selected 字段到 true 我在响应中收到的具有来自用户集合的photos-ids数组(用户ID是user-id字段)的ID的照片。 对此有何帮助?我很感激

我知道它是这样的:

User.findOne(body.req.user-id).exec(function (err, user) {
   /* update records here */ 
});

但说实话,我还没有找到解决问题的方法。

谢谢

1 个答案:

答案 0 :(得分:1)

请注意,Sails v0.10(目前处于测试阶段)支持关联,这将允许您创建单独的Photo模型并将其与User关联,为每个用户提供相关的照片集,而无需嵌入的文档。您可以使用npm install sails@beta安装v0.10,文档为here

话虽如此,您无法通过单个Sails方法调用完成您想要的操作。实际上,您甚至无法使用单个MongoDB调用来执行此操作。你能做的是:

User.findOne(req.param('user-id')).exec(function(err, user) {

    // Handle errors
    if (err) {return res.serverError(err);}
    if (!user) {return res.notFound();}

    // Set the specified photos "selected" key to true
    user.photos.forEach(function(photo) {
        // If the photo's ID is in the array that was sent, set
        // its "selected" key to "true"
        if (req.param('photo-ids').indexOf(photo.id) !== -1) {
            photo.selected = true;
        }
    });

    // Save the updated user
    user.save(function(err) {
        if (err) {return res.serverError(err);}

        // Return the updated record
        return res.json(user); 
    });

});

这使用Sails最佳实践循环遍历照片数组,更新需要更新的照片,并保存结果。

相关问题