问题
So in a relational DB I might have 2 tables, 'User' and 'Event', which have a many-to-many relationship, and thus a join table 'UsersEvents' say. Now I have some data that I want to store on this table other than the 2 IDs, something like a boolean called 'Enjoyed'.
I understand that in Mongo you would create embedded links between the tables e.g. using Mongoose
var Person = new Schema({
email: String,
events: [EventFeedback]
})
var Event = new Schema({ ... });
var EventFeedback = new Schema({
person: Schema.ObjectId,
event: Schema.ObjectId,
enjoyed: Boolean
});
but is this really the best way to model this? I would have thought that everything in EventFeedback could be in Person.events, which would be indexed by the Event._id? Or perhaps this is just a limitation of Mongoose?
回答1:
You would be better off using an Embedded Document rather than a link.
var Person = {
email: "joe.user@users.mongodb.org",
events: [
{code: "MONGONY2012", name: "Mongo NY", date: "5/23/2012", link: "http://www.10gen.com/events/mongo-nyc", enjoyed: true},
{code: "MONGOPHL2012", name: "Mongo Philly", date: "4/9/2012", link: "http://www.10gen.com/events/mongodb-philly", enjoyed: true}
]
}
You can query Mongo for an event easily, using dot notation:
db.people.find({"events.code": "MONGONY2012"})
回答2:
Try this way
var EventScheme = new Schema({ ... });
mongoose.model('Event', EventScheme);
var PersonScheme = new Schema({
email: String,
events: [{
event: {
type: mongoose.Schema.ObjectId,
ref: 'Event'
},
enjoyed: Boolean
}]
});
来源:https://stackoverflow.com/questions/9720464/modeling-data-on-a-many-to-many-join-in-mongo