Home > Mobile >  Query only one item in a nested mongoose object
Query only one item in a nested mongoose object

Time:10-20

I currently am trying to query an item inside of a mongoose object

module.exports.getAvatarsByLastMessages = function(messages, callback){
    const query = {lastMessage: {with: messages}}
    User.find(query, 'avatar username', callback);
  };

however it doesn't work because my lastMessage has multiple items in it, like so

{lastMessage: {with: 'foo', identifier:'bar', message:'lol'}}

How would I query what I want from just the "with:" object? My query has worked on other functions with only one item, and I got the same function to work by hardcoding in the identifier and message objects.

I'm not quite sure how to handle this and I wasn't even sure where to start googling or searching stack overflow for the problem.

CodePudding user response:

The "Query on Embedded/Nested Documents" documentation page is what you are looking for here.

The behavior of current syntax of using a document in the query predicate is described in the first section here. As you have observed, the semantics are not what you are looking for:

Equality matches on the whole embedded document require an exact match of the specified <value> document, including the field order.

Rather, you are looking to use dot notation, e.g.:

    const query = {'lastMessage.with': messages}}

Playground demonstration here.

  • Related