chemook78
chemook78

Reputation: 1198

How to find and edit the property of an array element inside a document in MongoDB/Node JS?

I have a MEAN stack app using the native MongoDB driver.

The user id of the logged in user is provided by Passport JS via req.user.id. Let's say req.user.id = "10154053694878424".

I can't figure out how to find a document in the database belonging to the user, find an element in an array, and update that element. The documents in the database look like this:

{
  "id": "10154053694878424", 
  "name: "John Doe",
  "city: "Amsterdam",
  "books": [{},{},{}],
  "requests": [
    {"title": "Harry Potter", "author": "JK Rowling", "status": "pending"},
    {"title": "Lord of the Rings", "author": "JR Tolkien", "status": "pending"}
  ] 
}

I have a route:

app.post("/changestatus", function(req,res){

  //req.body is an object with title of the book
  //for example: {"title": "Harry Potter"}

  //find user with req.user.id
  //check requests array and see which element matches "title":"Harry Potter"
  //change "status" to "accepted" instead of "pending"

)

How can I find the document in the database with the user ID, find the matching title element in books array and change the status property of the books array? I could find the User, return the document, edit that and then use updateOne to replace the document in the database. But there must be a more efficient way using findAndModify maybe?

Upvotes: 0

Views: 48

Answers (1)

Jairo Malanay
Jairo Malanay

Reputation: 1347

MongoDB Positional

// find data where id == req.user.id and requests.title = harry potter
db.collection
.update({ 
    id: req.user.id, 
    "requests.title": "Harry Potter" 
}, { 
    $set: { 
        "requests.$.status": "accepted" 
    } 
});

Upvotes: 1

Related Questions