Mongoose填充模型严格错误

时间:2018-01-29 14:04:41

标签: node.js mongodb mongoose

我有一个猫鼬模型如下:

var mongoose = require('mongoose');
var timestamps = require('goodeggs-mongoose-timestamps');
var Schema = mongoose.Schema;

var BeatSchema = new Schema({
    code: {
        type: String
    },
    removed: {
        type: Boolean,
        default: false
    }

},
{
    strict: false
});

BeatSchema.plugin(timestamps);
module.exports = mongoose.model('Beat', BeatSchema);

使用strict:false我可以插入任何不在模型模式中的属性并将它们保存到数据库中,问题是有时我会将objectIDS的属性插入到其他模式中。那么如何填充这些文件?

示例:

var params = {employee: employee._id, action: 'logout,code:"DL2"};
var beat = new Beat(params);
await beat.save();

如果我使用Beat.find({code:"DL2"})我只会将员工作为ID,那么如何在Beat.find中填充此模型?

1 个答案:

答案 0 :(得分:0)

我找到了答案,只需将虚拟属性添加到模型中并按其名称填充

BeatSchema.virtual('pEmployee', {
  ref: 'Employee',
  localField: 'employee',
  foreignField: '_id'
});