S.S*_*lan 7 mongoose mongodb node.js mongodb-query aggregation-framework
我有三个集合,例如User,Program和`议程。这些模型如下。
用户模型
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {type:String},
email: {type:String}
},{timestamps:true
}
);
module.exports = mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)
程序模型
const mongoose = require('mongoose');
const NoteSchema = mongoose.Schema({
name: {type:String},
timefrom: {type:Date},
timeto: {type:Date},
status: {type:String},
venue: {type:String},
timetype: {type:Number},
userid:{type:mongoose.Schema.Types.ObjectId,ref : 'User', required: true},
logo :{type:String,default: 'programe'}
},{timestamps:true
});
module.exports = mongoose.model('Program', NoteSchema);
Run Code Online (Sandbox Code Playgroud)
议程模型
const mongoose = require('mongoose');
const AgendaSchema = mongoose.Schema({
name: {type:String},
timefrom: {type:Date},
timeto: {type:Date},
status: {type:String},
proorder: {type:String},
proid:{type:mongoose.Schema.Types.ObjectId,ref : 'Program', required: true}
},
{timestamps:true}
);
module.exports = mongoose.model('Agenda', AgendaSchema);
Run Code Online (Sandbox Code Playgroud)
现在我只得到议程和节目数据。
议程控制器
// Retrieve and return all agenda from the database.
exports.findAll = (req, res) => {
Agenda.find()
.populate('proid')
//.populate('userid')
.then(agendas => {
res.send(agendas);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving agenda."
});
});
};
Run Code Online (Sandbox Code Playgroud)
当我转到此 URL 和GET方法时,我想填充agenda文档(完成)、相关program文档(完成)和相关user文档(我想要的)?
想要的查询是这样的
SELECT *
FROM users, programs, agendas
WHERE agendas.proid = programs.id AND programs.userid = users.id
Run Code Online (Sandbox Code Playgroud)
您可以使用$lookup聚合
Agenda.aggregate([
{ "$lookup": {
"from": Program.collection.name,
"let": { "proid": "$proid" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$proid" ] } } },
{ "$lookup": {
"from": User.collection.name,
"let": { "userid": "$userid" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$userid" ] } } },
],
"as": "userid"
}},
{ "$unwind": "$userid" }
],
"as": "proid"
}},
{ "$unwind": "$proid" }
])
Run Code Online (Sandbox Code Playgroud)
或与填充
Agenda.find()
.populate([{ path: 'proid', populate: { path: 'userid' }}])
Run Code Online (Sandbox Code Playgroud)
两者都会给你相同的结果
| 归档时间: |
|
| 查看次数: |
4258 次 |
| 最近记录: |