Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

node.js - Mongoosejs virtual populate

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'
});

caregiver schema:

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

Sample Object:

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

It now works perfectly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...