当我收到用户并显示拥有用户的所有实体时,我正在尝试显示所有信息。
我的想法是用户有多个地图,其中一个地图有一个信息与params。
当我在地图路线中通过id获取地图时,请填写show me info properties,但是当我在用户路线上使用populate时,请显示_id。
当我得到一个用户时,如何使用populate显示我的信息属性???
// Get User by id
app.get('/:id', (req, res) => {
var id = req.params.id;
User.findById({_id: id})
.populate('maps')
.populate('info')
.exec((err, user) => {
if (err) {
return res.status(500).json({
ok: false,
message: 'Error finding user'
});
}
if (!user) {
return res.status(404).json({
ok: false,
message: 'User with id ' + id + ' doesnt exist'
});
}
return res.status(200).json({
ok: true,
user: user
});
});
});
回应:
{
"ok": true,
"user": {
"maps": [
{
"visible": true,
"crossOrigin": "",
"layer": "",
"url": "",
"matrixSet": "",
"format": "",
"projection": "",
"paramsformat": "",
"paramsversion": "",
"paramslayers": "",
"paramsstyles": "",
"_id": "5b10f594f962fd1d109ea1d5",
"id": 0,
"owner": "5b10f57df962fd1d109ea1d4",
"name": "",
"keyName": "",
"type": "map",
"zIndex": "0",
"__v": 0,
"info": "5b10f5f2f962fd1d109ea1d7"
}
],
"_id": "5b10f57df962fd1d109ea1d4",
"id": 0,
"name": "User",
"email": "user@test.com",
"password": "user",
"__v": 1
}
}
用户模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
id: { type: Number, required: true },
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
maps: [{ type: Schema.Types.ObjectId, ref: 'map'}]
});
module.exports = mongoose.model('user', userSchema);
地图模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mapSchema = new Schema({
id: { type: Number, required: true },
owner: { type: Schema.Types.ObjectId, ref: 'user'},
name: { type: String, required: true },
keyName: { type: String, required: true },
type: { type: String, required: true },
visible: { type: Boolean, required: true, default: true },
zIndex: { type: String, required: true },
crossOrigin: { type: String, required: false, default: '' },
layer: { type: String, required: false, default: '' },
url: { type: String, required: false, default: '' },
matrixSet: { type: String, required: false, default: '' },
format: { type: String, required: false, default: '' },
projection: { type: String, required: false, default: '' },
paramsformat: { type: String, required: false, default: '' },
paramsversion: { type: String, required: false, default: '' },
paramslayers: { type: String, required: false, default: '' },
paramsstyles: { type: String, required: false, default: '' },
info: { type: Schema.Types.ObjectId, ref: 'info' }
});
module.exports = mongoose.model('map', mapSchema);