【问题标题】:Mongoosejs virtual populateMongoosejs 虚拟填充
【发布时间】:2017-10-08 12:25:51
【问题描述】:

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

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

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。它没有被填充。

【问题讨论】:

  • 你好。你能显示看护者模式的代码吗?
  • 注意:这里必须添加ref属性:userId: {type: Schema.ObjectId, unique: true},
  • @Sergaros 并没有真正理解你。你能详细说明一下吗?
  • 我的意思是你忘记了 ref 属性:userId: {type: Schema.ObjectId, unique: true, ref: 'user'}
  • @Sergaros 也不起作用。不知道发生了什么。 :(

标签: node.js mongoose mongoose-populate


【解决方案1】:

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

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

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

现在可以完美运行了。

【讨论】:

  • 耶!谢谢!我花了好几天才最终弄清楚这一点。虚拟字段没有明确包含stated in the docs。不知何故,我只记得关于 toJSON 的这一点——但我没有看到 toObject 的它,即使它在同一行。
【解决方案2】:

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

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

也可以直接使用toJSON/toObject:

doc.toObject({ virtuals: true })) // or doc.toJSON({ virtuals: true }))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 2017-02-13
    • 2018-03-05
    • 2019-06-17
    • 2018-05-20
    • 2017-04-04
    • 2014-09-20
    • 2020-12-08
    相关资源
    最近更新 更多