使用MongoDB/Meteor更新数组中的特定元素 [英] Updating a specific element in an array with MongoDB / Meteor

查看:42
本文介绍了使用MongoDB/Meteor更新数组中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"users_voted" : [ 
    {
        "user_id" : "AQG8ECLdBRJ4jwPMG",
        "score" : "down"
    }
]

想知道如何更新作为数组对象的users_voted字段.我需要更新特定的对象.我知道该对象所在的index,我只需要弄清楚如何在MongoDB/Meteor集合中更新该对象.

Wondering how I would go about updating the users_voted field which is an array objects. I need to have a specific object updated. I know the index at which this object is located, I simply need to figure out how I can update that object in a MongoDB / Meteor collection.

这是一些伪代码,我必须更好地解释我的意思.

This is some pseudo-code that I have to better explain what I mean.

Posts.update({_id: post_id}, {$set: {vote_score[index]: u_object}});

因此在此查询中,我知道indexpost_id以及u_object是我要放入数组中的对象,以代替该index处的任何对象.如果有人可以帮助我让我知道该怎么做,那就太好了.

So in this query I know index and post_id as well as u_object is the object that I am trying to put into the array in place of whatever object that was there at that index. If someone could help let me know how I should go about this, it would be great.

推荐答案

您不能将变量用作对象文字中的键.试试看:

You can't use variables as keys in an object literal. Give this a try:

var obj = {};
obj["users_voted." + index] = u_object;
Posts.update({_id: post_id}, {$set: obj});

这篇关于使用MongoDB/Meteor更新数组中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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