I am trying to define a mongo Schema using mongoose. I need to create an 'Event Schema' in which users are referenced. So I am populating the 'users' field with the referenced ObjectId of the user Schema. However I also need to add some extra fields on that user property which are specific to the event. So something like as follows:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var EventSchema = new Schema({
name: String,
date: Date,
users: [{
profile: {
type: Schema.ObjectId,
ref: 'User'
},
RankNumber: Number,
bibNumber: Number
}],
published: Boolean
});
mongoose.model('Event', EventSchema);
However this doesn't work. I am not sure the best way to do what I am trying to achieve.
So if I have a constructor function such as:
function User(bib, rank, profile) {
this.bib = bib;
this.rank = rank;
this.profile = profile;
}
and then I call that constructor and pass in a user id as the profile property, MongoDB will create a new id field. I get a JSON response like this:
{
"name": "Event name",
"_id: "mongoid",
"users": [
{
"bibNumber": "278",
"rankNumber": "21",
"profile": "users mongo _id number",
"_id": "a new mongo _id"
}
]
}
I need to populate the profile field. But the following won't work:
Event.find().populate('users').exec(function (err, events) {....
正如我在评论中所说,您必须使用:
Event.find(...).populate('users.profile').exec(...);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.