Modeling data on a many-to-many join in Mongo?

会有一股神秘感。 提交于 2020-01-04 13:23:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!