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.

1 Answer 1

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"}}})
Sign up to request clarification or add additional context in comments.

4 Comments

I can do the query in Mongo CLI, but can't do the query in loopback. After do some research, as stated here, github.com/strongloop/loopback-connector-mongodb I need to set allowExtendedOperators = true first. Thank you so much !
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 .
can we do this using loopback core API?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.