[英]Defining a property on mongo schema referencing another schema plus extra fields
I am trying to define a mongo Schema using mongoose. 我试图使用猫鼬定义一个mongo模式。 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. 因此,我使用用户架构的引用ObjectId填充“ users”字段。 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. 然后我调用该构造函数,并传入一个用户ID作为配置文件属性,MongoDB将创建一个新的ID字段。 I get a JSON response like this: 我收到这样的JSON响应:
{
"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')。exec(function(err,events){....
正如我在评论中所说,您必须使用:
Event.find(...).populate('users.profile').exec(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.