1

In my database I have something that looks like this:

 "_id" : ObjectId("5c0d9d54df58cb2fdc7f735a"),
"notificationMessages" : [ 
    {
        "message" : "Some message 1",
        "showNotification" : true,
        "projectId" : "5c0e40683500fe72a8e3ce8f"
    }, 
    {
        "message" : "Some message 2",
        "showNotification" : true,
        "projectId" : "5c0e6e113500fe72a8e3ce90"
    }
],

I want to update the "showNotification" to false when clicked on the concrete message on my client-side. To do this, I'm sending the index of what array I clicked on from the client-side to the nodejs server and I'm trying to use that result as the index for my update query, but it doesn't work. First I tried doing this:

  exports.delete_notification = async function(req,res) {

  let  arrayIndex = req.body.index;
console.log("This is the arrayIndex")
console.log(arrayIndex)


await User.update(
  {_id: req.session.userId},
  {$set: {'notificationMessages.' + arrayIndex + '.showNotification': false }}
)


res.status(200).json("done")

}

However, It seems as tho plusses are not allowed inside a update query: enter image description here (disregard the console.log(theString), theString doesn't exist I know, but that isn't the problem.)

So instead I tried doing this query

await User.update(
  {_id: req.session.userId},
  {$set: {'notificationMessages.arrayIndex.showNotification': false }}
)

This however results in following error:

(node:20656) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Cannot create field 'arrayIndex' in element {notificationMessages: [ { message: (....)

Anyone who can help me on how to properly update with a index that's recieved from the client-side?

2
  • 2
    See linked dupe. {$set: {['notificationMessages.' + arrayIndex + '.showNotification']: false }} Commented Dec 13, 2018 at 0:03
  • Thank you. Don't know how I didn't find that thread, but it solved my question Commented Dec 13, 2018 at 9:14

1 Answer 1

1

Array Indexes are accessible by bracket notation.

await User.update(
  {_id: req.session.userId},
  {$set: { notificationMessages[arrayIndex].showNotification: false }}
)

Try doing it without the single quote. If it doesn't work you can alternatively try to template string it like the following:

await User.update(
  {_id: req.session.userId},
  {$set: { `notificationMessages[${arrayIndex}].showNotification`: false }}
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.