Eri*_*ang 5 mongoose node.js mongoose-populate
项目组架构:
var ProjectGroupSchema = new Schema({
projectGroupId : String,
title : String
});
Run Code Online (Sandbox Code Playgroud)
项目架构:
var ProjectSchema = new Schema({
title : {type : String, default : '', required : true},
group : {type: String, ref: 'ProjectGroup' },
subscribers : [{type: String, ref: 'User' }]
});
Run Code Online (Sandbox Code Playgroud)
用户架构:
var UserSchema = new Schema({
userId : {type: String, require: true},
firstName : {type: String, required: true},
lastName : {type: String, required: true},
});
Run Code Online (Sandbox Code Playgroud)
然后,我可以进行以下填充:
project.findById(req.projectId})
.populate('subscribers')
.populate('group')
.exec(function(err, project){
console.log(project);
});
Run Code Online (Sandbox Code Playgroud)
请注意,参考字段不是对象ID。
在此示例中,项目模式具有对项目组和订户的引用字段,这使得上述填充成为可能。
如果我想获得一个ProjectGroup对象,该对象包含该组下的所有项目,并且每个项目都包含其订阅者,该怎么办?
我想说的是,我正在寻找“反向”人群,即根据子模式中定义的引用填充父对象。目前,我先使用async来查询ProjectGroup,然后再根据projectGroupId查询项目。
谢谢!
如果要获取一个ProjectGroup对象,该对象包含该组下的所有项目。您可以使用“ 填充虚拟”。(猫鼬版本> 4.5.0)
在您的模式文件中创建一个虚拟模式。
ProjectGroupSchema.virtual('projects', {
ref: 'Project', // The model to use
localField: 'projectGroupId', // Your local field, like a `FOREIGN KEY` in RDS
foreignField: 'group', // Your foreign field which `localField` linked to. Like `REFERENCES` in RDS
// If `justOne` is true, 'members' will be a single doc as opposed to
// an array. `justOne` is false by default.
justOne: false
});
Run Code Online (Sandbox Code Playgroud)
并在以下查询:
ProjectGroup.find().populate('projects').exec(function(error, results) {
/* `results.projects` is now an array of instances of `Project` */
});
Run Code Online (Sandbox Code Playgroud)
如果看不到虚拟零件,请设置{ toJSON: { virtuals: true } }模型。
var ProjectGroupSchema = new Schema({
projectGroupId : String,
title : String
}, { toJSON: { virtuals: true } });
Run Code Online (Sandbox Code Playgroud)
您可以通过使用聚合函数来实现这一点。首先按“projectGroup”对项目进行分组,然后填充结果。
project.aggregate([
{$group: {_id: "$group", projects: {$push: "$$ROOT"}}}
],
function(err,results) {
user.populate( results, { "path": "projects.subscribers" }, function(err,results) {
if (err)
console.log(err);
res.send(results);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2657 次 |
| 最近记录: |