我有两个模型,
var locationSchema = mongoose.Schema({
name: String,
users: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
});
var userSchema = mongoose.Schema({
name: String,
email: String
});
我希望获取所有包含特定用户的位置信息。例如,有以下数据:
Location Users
A [1,2,3]
B [1,4,5]
C [6]
比如,我想找到所有拥有用户1的位置。我尝试了以下方法,但都不起作用:
var locationModel = mongoose.model('Location', locationSchema);
locationModel.find({
users : { $in: user }
});
locationModel.find({
'users._id' : user._id
});
locationModel.find({
'users.$oid' : user._id
});
locationModel.find({
'users.id' : user._id
});
有什么想法吗?
_id
方面可能有效,但如果它适合您的用例,您可能需要查看嵌入式文档。如果您可以这样做,则从用户模式中查询相关信息将变得更加容易。 - Neil Lunn