本文介绍了Mongoose.js虚拟填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a circle model in my project:

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虚拟填充,但无法使其正常工作.这似乎是完全相同的问题: https://github.com/Automattic/mongoose/issues/4585

I have tried virtual populate for mongoosejs but I am unable to get it to work.This seems to be the exact same problem: 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);
    });

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

I am only getting the object id's in the result. It is not getting populated.

推荐答案

找出问题所在.默认情况下,虚拟字段不包含在输出中.在圈子模式中添加此代码后:

Figured out what the problem was.By default, the virtual fields are not included in the output.After adding this in circle schema:

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

circleSchema.set('toObject', { virtuals: true });
circleSchema.set('toJSON', { virtuals: true });

现在可以正常使用了.

这篇关于Mongoose.js虚拟填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 11:17