简体   繁体   中英

Mongoose find value from other collection

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

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

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 )

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){
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM