Mongoosejs虚拟填充

Him*_*ain 10 mongoose node.js mongoose-populate

我的项目中有一个圆圈模型:

var circleSchema = new Schema({
//circleId: {type: String, unique: true, required: true},
patientID: {type: Schema.Types.ObjectId, ref: "patient"},
circleName: String,
caregivers: [{type: Schema.Types.ObjectId}],
accessLevel: Schema.Types.Mixed
});

circleSchema.virtual('caregiver_details',{
    ref: 'caregiver',
    localField: 'caregivers',
    foreignField: 'userId'
});
Run Code Online (Sandbox Code Playgroud)

看护者架构:

var cargiverSchema = new Schema({
    userId: {type: Schema.ObjectId, unique: true},  //objectId of user document
    detailId: {type: Schema.ObjectId, ref: "contactDetails"},
    facialId: {type: Schema.ObjectId, ref: "facialLibrary"}, //single image will be enough when using AWS rekognition
    circleId: [{type: Schema.Types.ObjectId, ref: "circle"}],           //multiple circles can be present array of object id
});
Run Code Online (Sandbox Code Playgroud)

示例对象:

{ 
    "_id" : ObjectId("58cf4832a96e0e3d9cec6918"), 
    "patientID" : ObjectId("58fea8ce91f54540c4afa3b4"), 
    "circleName" : "circle1", 
    "caregivers" : [
        ObjectId("58fea81791f54540c4afa3b3"), 
        ObjectId("58fea7ca91f54540c4afa3b2")
    ], 
    "accessLevel" : {
        "location\"" : true, 
        "notes" : false, 
        "vitals" : true
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过mongoosejs的虚拟填充,但我无法让它工作.这似乎是完全相同的问题:https://github.com/Automattic/mongoose/issues/4585

circle.find({"patientID": req.user._id}).populate('caregivers').exec(function(err, items){
        if(err){console.log(err); return next(err) }
        res.json(200,items);
    });
Run Code Online (Sandbox Code Playgroud)

我只在结果中获取对象id.它没有人口稠密.

Him*_*ain 30

找出问题所在.默认情况下,虚拟字段不包含在输出中.在圈架构中添加此内容后:

circleSchema.virtual('caregiver_details',{
    ref: 'caregiver',
    localField: 'caregivers',
    foreignField: 'userId'
});

circleSchema.set('toObject', { virtuals: true });
circleSchema.set('toJSON', { virtuals: true });
Run Code Online (Sandbox Code Playgroud)

它现在完美无缺.

  • 耶!谢谢!我花了几天的时间终于弄清楚了这一点。虚拟字段未明确包含 [文档中所述](https://mongoosejs.com/docs/guide.html#virtuals)。不知何故,我只记得关于 toJSON 的这一点——但我没有看到 toObject 即使它在同一行上。 (2认同)