0

here is my models:

var RaceSchema = new mongoose.Schema({
    name: {
        type: String
    },
    owner:{
        type: mongoose.Schema.ObjectId, ref:"user"
    }
});
var UserSchema = new mongoose.Schema({
    username: { 
        type: String
    }
});

Here is an example of my collections:

//Races
{
    "_id": {
        "$oid": "5b5740c54befec2594ce4cb0"
    },
    "name": "Race1"
    "owner": {
        "$oid": "5b34f870e1eef640f8cb43e4"
    }
}
//User
{
    "_id": {
        "$oid": "5b34f870e1eef640f8cb43e4"
    },
    "username":"admin"
}

I want to find races whose owner matchs with field username. I mean: "I want to find races whose owner is admin"

I'm trying this with:

Race.find().populate('users', {username: 'admin'}).exec(function (err, races) {
    ....
}

But always the result is the same, the search gives me all races.

EDIT 1

SQL Sentence would be:

Select * FROM Races,Users WHERE owner=user._id AND user.username='admin' 

Or something like that

Community
  • 1
  • 1
ipakto
  • 13
  • 4

3 Answers3

1

Finally I did. SOLUTION:

Here is my code:

var query=[{
        "$lookup": {
            "from": "users",
            "localField": "owner",
            "foreignField": "_id",
            "as": "user"
        }
    },{
        "$unwind": "$user"
    },{
        "$match": {
            "$and": [{
                "user.username": username
            }]
        }
    }];
Race.aggregate(query, function (err, races){
    ....
}
Community
  • 1
  • 1
ipakto
  • 13
  • 4
0

once you get all the races use array method filter

example:

let adminRaces = races.filter(x=>x.owner['$oid'] === admin._id['$oid'])

here's reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

0

To get data from two different collections you will need to use aggregate function with $lookup (see the docs)

You can find its equivalent in mongoose (see this question)

laxman
  • 1,781
  • 4
  • 14
  • 32
  • I dont want get data from two different collections. SQL Sentence would be: Select * FROM Races,Users WHERE owner=user._id AND user.username='admin' Or something like that – ipakto Jul 24 '18 at 18:16