[英]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 . 我想找到所有者与字段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. 但是结果总是一样的,搜索给了我所有种族。
SQL Sentence would be: SQL语句为:
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 这是参考: https : //developer.mozilla.org/zh-CN/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 ) 要从两个不同的集合中获取数据,您将需要对$ lookup使用聚合函数( 请参阅docs )
You can find its equivalent in mongoose ( see this question ) 您可以在猫鼬中找到其等效项( 请参阅此问题 )
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){
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.