猫鼬:使用其他模型的架构

时间:2018-12-24 10:09:38

标签: node.js mongodb express mongoose mongoose-schema

我有一个模型“模板”

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中使用我的模板架构?

1 个答案:

答案 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
    });