0

I want to update a value of a sub-document where a message has a specific id and an user id is in a recipient array. I want to update a value of the matched object with the specified user id.

When I run the following query on the MongoDB CLI, everything works and the value is updated:

db.getCollection('messages').update({
  _id : ObjectId("57d7edb8c497a75a6a7fde60"),
  "recipients.userId" : "5789127ae2bcc79326462dbc"
},{
  $set : {"recipients.$.read": true}
});

But when I run the following query via JS in my FeathersJS application:

messageService.update({
  _id : '57d7edb8c497a75a6a7fde60',
  "recipients.userId" : "5789127ae2bcc79326462dbc"
},{
  $set: {"recipients.$.read": true}
}).then(function(e) {
  console.log(e)
}).catch(function(e) {
  console.log(e);
});

I get the error:

GeneralError: The positional operator did not find the match needed from the query. Unexpanded update: recipients.$.read

What am I doing wrong?

And is there a better way of updating many messages at once?

Thanks!

tan
  • 51
  • 1
  • 8

1 Answers1

2

For updating one or multiple records by a query you need to call the service method by setting id to null and putting the query into params.query:

messageService.update(null, {
  $set: {"recipients.$.read": true}
}, {
  query: {
    _id : '57d7edb8c497a75a6a7fde60',
    "recipients.userId" : "5789127ae2bcc79326462dbc"
  }
}).then(function(e) {
  console.log(e)
}).catch(function(e) {
  console.log(e);
});
Daff
  • 43,734
  • 9
  • 106
  • 120
  • Makes sense for me, but when I run this code I get an "Error: [object Object]" response – tan Sep 19 '16 at 16:06
  • 1
    Maybe https://docs.feathersjs.com/debugging/readme.html can help to get a better error message (might be a bug that it is not converting the error properly). – Daff Sep 19 '16 at 21:20