我有一个模型“模板”
var Schema = new mongoose.Schema({
tId: { type: Number, unique: true },
type: {
type: String, required: true},
devName: { type: String, required: true, trim: true },
subject: { type: String, required: true, trim: true },
});
module.exports = mongoose.model('Template', schema, "template");
我想在另一个模型“ TemplateHistory”中保留其历史记录 我不想再次写模式,
var HistorySchema = new mongoose.Schema({
id: number,
template:{
tId: { type: Number, unique: true },
type: {
type: String, required: true},
devName: { type: String, required: true, trim: true },
subject: { type: String, required: true, trim: true }
}
});
如何在上面的HistorySchema中使用我的模板架构?
答案 0 :(得分:0)
尝试这样映射它
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var HistorySchema = new mongoose.Schema({
id: number,
templateId: { type: Schema.Types.ObjectId, ref: 'Template', required: true }
});
//add virtual
HistorySchema.set('toObject', { virtuals: true });
HistorySchema.set('toJSON', { virtuals: true });
HistorySchema.virtual('template', {
ref: 'Employee',
localField: 'templateId',
foreignField: '_id',
justOne: true
});
在您的服务或控制器中:
HistorySchema
.find({})
.populate('template')
.exec( function(err, history)
{
res.json(history); // history[0].template
});