动态创建Meteor.js MongoDB查询 [英] Dynamically create Meteor.js MongoDB query

查看:68
本文介绍了动态创建Meteor.js MongoDB查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我很难使它正常工作.我有一个名为猫"的Mongo集合,另一个名为行"的集合. 'cats'中的cat字段是currentCat.然后,我希望能够通过引用带有_id的现有文档来更新行"中的文档.那里没有问题.但是,对于每个currentCat,我都希望将一个元素添加到行"文档中,并以currentCat作为字段,并使用其他值作为值(currentPer).我想到了这个:

For some reason I'm having a hard time getting this to work. I have a Mongo collection called 'cats', and another called 'rows'. The cat field in 'cats' is currentCat. Then I want to be able to update a document in 'rows' by referring to a preexisting document with an _id. No problems there. But for every currentCat, I want to add an element to the 'rows' document with currentCat as the field and something else as the value (currentPer). I came up with this:

var cats = Cats.find({owner: Meteor.userId()}, {fields: {cat: 1, per: 1}});

cats.forEach(function(cats) { //Inserts the rest of the row
  var currentCat = cats['cat'];
  var currentPer = cats['per'];
  var currentAmount = Math.round(amount*currentPer*100)/100;

  Rows.update(
    { _id: row },
    { $push: { currentCat: currentAmount } }
  );
});

(row是我要修改的文档的ID)

(row is the id of the document I want modified)

当然,它不能按预期工作,只是插入...{currentCat: 57}而不是变量currentCat的值.接下来,我尝试创建查询对象(如此处所述):

Of course, it doesn't work as expected and just inserts ...{currentCat: 57} instead of the value of the variable currentCat. Next, I tried creating a query object (as described here):

var query = ({ _id: row }, { $push: { currentCat: currentAmount } })

这也失败了,但是这次出现了一个极好的描述性错误消息:

That also failed, but this time with a wonderfully descriptive error message:

Error: Invalid modifier. Modifier must be an object.

任何帮助将不胜感激,因为我已经花费了数小时并且在此上进行了无数的Google搜索(尽管答案可能很明显而且我只是看不到-我仍然想在PHP之后适应Meteor)

Any help would be appreciated, as I've spent hours and countless Google searches on this (although the answer is probably obvious and I just can't see it - I'm still trying to get used to Meteor after PHP).

编辑:我希望完成的文档看起来像这样:

EDIT: I want the finished document to look something like this:

 { "_id" : "PshEYKebccw7eYaTo", 
   "createdAt" : ISODate("2014-11-26T00:52:51.840Z"),
   "cat1" : 312,
   "cat2" : 564,
   "owner" : "GiWCb8jXbPfzyc5ZF",
   "text" : "asdf" 
}

推荐答案

$push仅适用于数组.根据您的Row文档示例,您实际上并不需要在这里进行数组操作.

$push is only for operating on arrays. Based on your example of a Row document, you don't really want an array operation here.

尝试仅在行"文档中为每个新的cat值设置字段.

Try just setting fields on the Row document for each new cat value.

  var catData = {};
  catData[currentCat] = currentAmount;
  // As an example, catData now looks like {'cat1': 312}

  Rows.update(
    { _id: row },
    { $set: catData }
  );

这篇关于动态创建Meteor.js MongoDB查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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