I have FlashcardSchemas and PackageSchemas in my design. One flashcard can belong to different packages and a package can contain different flashcards.
Below you can see a stripped down version of my mongoose schema definitions:
// package-schema.js var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var PackageSchema = new Schema({ id : ObjectId, title : { type: String, required: true }, flashcards : [ FlashcardSchema ] }); var exports = module.exports = mongoose.model('Package', PackageSchema); // flashcard-schema.js var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var FlashcardSchema = new Schema({ id : ObjectId, type : { type: String, default: '' }, story : { type: String, default: '' }, packages : [ PackageSchema ] }); var exports = module.exports = mongoose.model('Flashcard', FlashcardSchema);
As you can see from the comments above, these two schema definitions belong to separate files and reference each other.
I get an exception stating that PackageSchema is not defined, as expected. How can I map a many-to-many relation with mongoose?
Many to Many relationships are a type of mongodb relationship in which any two entities within a document can have multiple relationships.
Mongoose doesn't allow to use multiple databases in single mongoose instance as the models are build on one connection.
To model relationships between connected data, you can reference a document or embed it in another document as a sub document. Referencing a document does not create a “real” relationship between these two documents as does with a relational database. Referencing documents is also known as normalization.
I am new to node, mongoDB, and mongoose, but I think the proper way to do this is:
var PackageSchema = new Schema({ id: ObjectId, title: { type: String, required: true }, flashcards: [ {type : mongoose.Schema.ObjectId, ref : 'Flashcard'} ] }); var FlashcardSchema = new Schema({ id: ObjectId, type: { type: String, default: '' }, story: { type: String, default: '' }, packages: [ {type : mongoose.Schema.ObjectId, ref : 'Package'} ] });
This way, you only store the object reference and not an embedded object.
You are doing it the right way, however the problem is that you have to include PackageSchema in the the flashcard-schema.js, and vice-versa. Otherwise these files have no idea what you are referencing
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; PackageSchema = require('./path/to/package-schema.js') var FlashcardSchema = new Schema({ id : ObjectId, type : { type: String, default: '' }, story : { type: String, default: '' }, packages : [ PackageSchema ] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With