当前位置: 动力学知识库 > 问答 > 编程问答 >

node.js - Show referenced documents details via mongoose REST?

问题描述:

I have a schema that has ref fields in it:

exports.metricSchema = new Schema({

metricGroup: {type: mongoose.Schema.Types.ObjectId, ref: 'metricGroupSchema', required: true},

metricType: {type: mongoose.Schema.Types.ObjectId, ref: 'metricTypeSchema', required: true},

key: {unique: true, type: String, required: true},

name: {type: String, required: true},

description: String

});

I define and register them as:

var MetricGroupResource = apprest.resource = restful.model('MetricGroup', schemas.metricGroupSchema)

.methods(defaultRestMethods);

MetricGroupResource.register(apprest, '/rest/metricgroup');

and it will show in mongoose REST as this:

{

"_id": "58a20f5f04ef5789d3ef8fb7",

"name": "Tangle Index",

"key": "TI",

"metricType": "58a20f43f1bbfe89c86bf602",

"metricGroup": "58a20f43f1bbfe89c86bf600",

"__v": 0

}

Is there a way to have mongoose show details of the referenced model without building custom populated views?

网友答案:

You can use populate function, you can read the documentation here

Example:

MyModel.find(query)
.populate(
    [
        {
            'path': 'metricGroup'
        },
        {
            'path': 'metricType'
        }
    ]
)
.exec(function (err, _array) {
  if (err) {
    console.log(err);
  }
  console.log(_array); //print array with metricGroup and metricType fields with details
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: