문제

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 ;)

도움이 되었습니까?

해결책

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);
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top