Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoosejs虚拟填充_Node.js_Mongoose_Mongoose Populate - Fatal编程技术网

Node.js Mongoosejs虚拟填充

Node.js Mongoosejs虚拟填充,node.js,mongoose,mongoose-populate,Node.js,Mongoose,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.Typ

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

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'
});
医务人员模式:

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
});
示例对象:

{ 
    "_id" : ObjectId("58cf4832a96e0e3d9cec6918"), 
    "patientID" : ObjectId("58fea8ce91f54540c4afa3b4"), 
    "circleName" : "circle1", 
    "caregivers" : [
        ObjectId("58fea81791f54540c4afa3b3"), 
        ObjectId("58fea7ca91f54540c4afa3b2")
    ], 
    "accessLevel" : {
        "location\"" : true, 
        "notes" : false, 
        "vitals" : true
    }
}
我已经尝试了mongoosejs的虚拟填充,但是我无法让它工作。 这似乎是完全相同的问题:


我只得到结果中的对象id。它没有被填充。

找到了问题所在。 默认情况下,输出中不包括虚拟字段。 在圆模式中添加此后:

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

circleSchema.set('toObject', { virtuals: true });
circleSchema.set('toJSON', { virtuals: true });
现在它可以完美地工作。

如果使用expressJs res.json方法,只需添加:

yourSchema.set('toJSON', { virtuals: true });
或者您可以直接使用:


你好您可以显示医务人员模式的代码吗?注意:您必须在此处添加ref属性:userId:{type:schema.ObjectId,unique:true},@Sergaros没有真正理解您。我的意思是你忘记了ref属性:userId:{type:Schema.ObjectId,unique:true,ref:'user'}@Sergaros,它们也不起作用。不知道发生了什么事(YEEEEES!谢谢!我花了好几天的时间才最终弄明白。虚拟字段没有包括得那么清楚。不知何故,我只记得关于toJSON的这一点——但我没有看到toObject的这一点,即使它在同一行上。
yourSchema.set('toJSON', { virtuals: true });
doc.toObject({ virtuals: true })) // or doc.toJSON({ virtuals: true }))