node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合
问题描述
我有三个集合,例如User
、Program
和 `Agenda。这些模型如下。
用户模型
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {type:String},
email: {type:String}
},{timestamps:true
}
);
module.exports = mongoose.model('User', UserSchema);
程序模型
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);
议程模型
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);
现在我只得到议程和节目数据。
议程控制器
// 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."
});
});
};
当我转到此 URL 和GET
方法时,我想填充agenda
文档(完成)、相关program
文档(完成)和相关user
文档(我想要的)?
像这样的通缉查询
SELECT *
FROM users, programs, agendas
WHERE agendas.proid = programs.id AND programs.userid = users.id
解决方案
您可以使用$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" }
])
或使用填充
Agenda.find()
.populate([{ path: 'proid', populate: { path: 'userid' }}])
两者都会给你相同的结果
推荐阅读
- postgresql - PostgreSQL 选择最接近的上个月六月
- c - Linux 内核 - 读取/写入文件
- ruby-on-rails - Rails 5 POST请求添加额外参数?
- php - 对 PHP.INI 的编辑没有生效
- javascript - Vuex - ...从模板调用mapActions:无法读取未定义的属性“调度”
- c - 如何在没有 Windows 头文件的情况下使用 NtCurrentTeb()?
- blazor - 升级到 0.6.0 后无法构建 Blazor 项目
- excel - 键入时具有自动完成和搜索功能的 VBA 组合框
- bitbucket-server - 如何创建一个拒绝使用错误文件名推送的 BitBucket 挂钩?
- image - 如何在 Flutter/Dart 中“将参数转换为 'dart.ui::Image'”