3

I'm use loopback and mongodb. Right now I have a Model and one of its property type is array of object. The document in mongo will look like this

{
  "id": "123123213",
  "name": "Some Name",
  "colors": [{
    "colorId": "1"
    "colorName: "Red"
  }, {
    "colorId": "2",
    "colorName: "Blue"
  }]
}

Now i have a requirements to querying update and delete specific object in colors array. Let say i need to update the colorName only in colorId 2 to Green. And delete the Color object which the colorId is 2.

How to achieve this in loopback? Please advise ! Thank you.

Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
Anton
  • 75
  • 7

1 Answers1

4

In mongo CLI, you can use $ (positional) to update matching element from an embedded array document

update

> db.colors.update({"colors.colorId" :"2"}, {$set : {"colors.$.colorName" : "Green"}})

use $pull to delete

> db.colors.update({}, {$pull : {"colors" : {"colorId" : "2"}}})
Saravana
  • 12,647
  • 2
  • 39
  • 57
  • I can do the query in Mongo CLI, but can't do the query in loopback. After do some research, as stated here, https://github.com/strongloop/loopback-connector-mongodb I need to set `allowExtendedOperators = true` first. Thank you so much ! – Anton Feb 05 '18 at 01:19
  • how do you add push a new object to the array of object in loopback without using the $push ? ( in this case how do add a new object to the colors array ) ? any help would be appreciated . – Franklin Pious Feb 06 '18 at 09:31
  • can we do this using loopback core API? – Manish Balodia Feb 07 '18 at 08:11
  • 1
    @ManishBalodia yes we can, use this code instead `YourModel.updateAll({"colors.colorId":"2"}, {{"$set": {"colors.$.colorName": "Green"}}})`. But dont forget to set `"allowExtendedOperators": true` in your datasource.json first – Anton Feb 17 '18 at 03:10