gpt4 book ai didi

node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合

转载 作者:可可西里 更新时间:2023-11-01 09:13:23 25 4
gpt4 key购买 nike

我有三个集合,例如 UserProgram 和 `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 文档(完成)和相关的用户文档(这个我要)?

像这样的查询

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' }}])

两者都会给你相同的结果

关于node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51724786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com