如何在MeteorJS中更新MongoDB集合上的子文档数组 [英] How to Update An Array of Subdocuments on a MongoDB Collection in MeteorJS

查看:98
本文介绍了如何在MeteorJS中更新MongoDB集合上的子文档数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在更新Meteor中的mongo集合时遇到问题。

I'm having a problem updating a mongo collection in Meteor.

也许我只是不明白 $ addtoset 有效。

Perhaps I just don't understand how $addtoset works.

这是我的基本文档,或多或少都在我的 fixtures.js 中我在哪里初始化我的项目:

Here is my basic document, more or less this is in my fixtures.js where I initialize my project:

var someUser = Meteor.users.findOne("W9YEs84QFhZzJeB6j");

var NewIdea = Ideas.insert({
  title: "This Is a Title",
  body: "Blah Blah Blah Body Goes Here",
  userId: someUser._id,
  author: someUser.profile.name,
  timestamp: new Date(now - 5 * 3600 * 1000),
  score: [],
  overallScore: 0,
  votedOnBy: [],
  timesVotedOn: 0
});

这是我希望更新后的样子:

Here is what I want it to look like after the update:

{
  _id: "bKXXrpYmppFBfq9Kx",
  title: "This Is a Title",
  body: "Blah Blah Blah Body Goes Here",
  userId: "W9YEs84QFhZzJeB6j",
  author: "Users Name",
  timestamp: ISODate("2016-06-07T20:37:05.775Z"),
  score: [
    {
      userId: ""W9YEs84QFhZzJeB6j",
      score: 1
    }
  ],
  overallScore: 1,
  votedOnBy: [
    "W9YEs84QFhZzJeB6j"
  ],
  timesVotedOn: 1
}

这是我用来更新的代码(不起作用):

Here is the code I'm using to update (which is not working):

Ideas.update("bKXXrpYmppFBfq9Kx", {
  $addToSet: {score: {userId: someUser._id, score: 1}},
  $inc: {overallScore: 1},
  $addToSet: {votedOnBy: someUser._id},
  $inc: {timesVotedOn: 1}
});

这是mongo控制台中的实际文档(上移后日期):

Here's the actual document from mongo console (after the update):

{
  "_id" : "bKXXrpYmppFBfq9Kx",
  "title" : "This Is a Title",
  "body" : "Blah Blah Blah Body Goes Here",
  "userId" : "W9YEs84QFhZzJeB6j",
  "author" : "Users Name",
  "timestamp" : ISODate("2016-06-07T20:37:05.775Z"),
  "votedOnBy" : [
    "W9YEs84QFhZzJeB6j"
  ],
  "timesVotedOn" : 1
}

请注意 overallScore 得分根本不存在。

我是Meteor和Mongo的新手(也许很明显)。有人知道我在这里做错什么吗?还是我需要什么以便我可以正确进行此更新?

I'm new to Meteor and Mongo (perhaps that's obvious). Does anyone know what I'm doing wrong here? Or what I need so that I may do this update right?

推荐答案

重要的是要记住,修饰符只是一个对象。以下对象文字:

It's important to remember that the modifier is just an object. The following object literal:

{
  a: 1, b: 1,
  a: 2, b: 2
}

评估为:

{ a: 2, b: 2 }

在您的代码中,相同的想法适用于 $ addToSet $ inc 键。要解决此问题,请像这样编写您的 update

In your code, the same idea applies to the $addToSet and $inc keys. To fix it, write your update like this:

Ideas.update("bKXXrpYmppFBfq9Kx", {
  $addToSet: {
    score: { userId: someUser._id, score: 1 },
    votedOnBy: someUser._id
  },
  $inc: {
    overallScore: 1,
    timesVotedOn: 1
  }
});

这篇关于如何在MeteorJS中更新MongoDB集合上的子文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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