Mongo查询(带有位置运算符)不适用于猫鼬 [英] Mongo query (with positional operator) does not work in mongoose

查看:72
本文介绍了Mongo查询(带有位置运算符)不适用于猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个包含果园的数据库集合,一个对象看起来像这样:

Given a database collection with orchards, one object looks like this:

{
"orchardId" : ObjectId("5391c137722b051908000000"),
"trees" : [ 
    {
        "name" : "apple",
        "fruits" : []
    }, 
    {
        "name" : "pear",
        "fruits" : [ 
            ObjectId("54c54291d93236150f00004e"), 
            ObjectId("54c542c9d93236150f000062")
        ]
    }
]
}

我想动态地将水果添加到特定的树上.我知道我可以在mongo中执行以下操作:

I want to dynamically add a fruit to a specific tree. I know I can do this in mongo with:

db.orchards.update(
    ({"orchardId": ObjectId("5391c137722b051908000000")},
    {"trees" : { $elemMatch: {"name":"apple"}}}),
    { $push: { "trees.$.fruits": ObjectId("54c542c9d900000000001234") }}
)

所以,如果我是对的,那应该是猫鼬了.

So, if I'm right this should be this in mongoose:

orchards.update(
    ({"orchardId": ObjectId.fromString(orchard.id)},
    {"trees" : {$elemMatch: {"name": "apple"}}}),
    {$push: {"trees.$.fruits": ObjectId("54c542c9d900000000001234") }},function(err, data){ ...

但是随后我收到一条错误消息:[TypeError:无法调用未定义的方法'path']

But then I get an error saying: [TypeError: Cannot call method 'path' of undefined]

猫鼬似乎无法处理位置运算符($),因为当我将$更改为0时,它确实起作用.

It looks like mongoose can't handle the positional operator (the $) because when I change the $ with a 0 it does work.

我如何用猫鼬做这项工作?

How do I make this work in mongoose?

推荐答案

在您的代码示例中,您有括号中应有括号的地方,因此应改为:

In your code sample you've got parens where you should have braces, so it should be like this instead:

orchards.update({
    "orchardId": ObjectId(orchard.id),
    "trees": {$elemMatch: {"name": "apple"}}
  },
  {$push: {"trees.$.fruits": ObjectId("54c542c9d900000000001234") }},
  function(err, data){ ...

这篇关于Mongo查询(带有位置运算符)不适用于猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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