我有两个文档架构,我试图使用“虚拟”将它们链接起来,以便文档A可以拥有文档B,然后使用如下所示的句柄来相应地显示它:{{#eachdocumentA.documentB}},两种模式均正确填充数据库。我们将不胜感激,我认为文档A的控制器中不需要任何其他帮助,因此我没有提供它,但是如果我错了,请告诉我,我将进行相应更新。谢谢。
文档模型(带有虚拟):
const mongoose = require('mongoose');
const validator = require('validator');
mongoose.Promise = global.Promise;
const mongodbErrorHandler = require('mongoose-mongodb-errors');
const passportLocalMongoose = require('passport-local-mongoose');
const teamSchema = new mongoose.Schema({
teamName:
{
type: String,
trim: true
},
addr1: {
type: String,
trim: true
},
addr2: {
type: String,
trim: true
},
teamType: {
type: String
},
county: {
type: String
},
phNum: {
type: String
},
email: {
type: String
},
teamType: {
type: String
},
coach: {
type: mongoose.Schema.ObjectId,
ref: 'User'
},
teamCode:
{
type:String
},
col1:
{
type: String
},
col2:
{
type: String
},
jerseyType:
{
type: String
}
});
teamSchema.virtual('videos', {
ref: 'Video',
localField: '_id',
foreignField: 'team',
});
module.exports = mongoose.model('Team', teamSchema);
文档B型号:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const videoSchema = new mongoose.Schema ( {
team : {
type: mongoose.Schema.ObjectId,
ref: 'Team',
required: true,
},
code : {
type: String,
trim: true,
required: 'Code cannot be Empty!',
},
title : {
type: String,
trim: true,
required: 'Title Cannot be Empty!',
},
created : {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('Video', videoSchema);
文档B控制器:
const mongoose = require('mongoose');
const Video = mongoose.model('Video');
exports.addVideo = async (req, res) => {
await (new Video(req.body)).save();
res.redirect('/dashboard/video');
};
exports.getVideoAnalysisPage = (req, res) =>
{
res.render('dashboard/video.hbs',{ title: "Video", cybersecurity: `${req.csrfToken()}`});
};
把手文件中的参考
{{#each team.videos}}
<tr>
<td class="vidThumb"></td>
<td class="vidInfo"><b><span style="font-size: 20px">{{this.title}}</span></b><br><span style="font-size: 12px">Uploaded: {{this.created}}</span></td>
</tr>
{{/each}}