Mongo query (with positional operator) does not work in mongoose

For a database collection with gardens, one object is as follows:

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

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

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

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

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

But then I get the error message: [TypeError: cannot call the "path" method from undefined]

It seems that the mongoose cannot handle the positioning operator ( $ ), because when I change $ from 0, it works.

How to make this work in mongoose?

+2
source share
1 answer

In your code example, you have paranas in which you should have curly braces, so it should be like this:

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

All Articles