0

In MongoDB/Mongoose i have a Server collection which got this element ...

  owners: [{

    type: String,
    ref: 'User'

  }]

The owners array contains many id linked to an User collection. Very simple. It populates correctly and everything.

In a Server.find() i must retrieve the list of servers that got a specific owner. So the correct query would be something like

      FIND IN SERVER WHERE (OWNERS ARRAY) CONTAINS (THIS ID)

Which i translated in Mongoose as ...

      Server.find({'owners.$': user._id}).exec(function(error, servers) {

        console.log(servers);

      });

I was thinking "owners.$" let us search through a collection-array and in this case compare it with user._id but I was wrong, it seems the ".$" can only be used in a ".update()" query.

How can you do the same for a find ? What is the equivalent ? I'm searching everywhere and can't find out the solution ...

Thank you people ;)

1 Answer 1

1

You're making it more complicated than it needs to be as you can directly filter on array properties just as you would a normal property:

Server.find({owners: user._id}).exec(function(error, servers) {
    console.log(servers);
});
Sign up to request clarification or add additional context in comments.

1 Comment

How my god ! Thank you that was so simple I didn't even try ! :)

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.