Andre M
Andre M

Reputation: 7554

Structuring a list of favourites with MongoDB & Mongoose?

I am starting to use mongo, and I would like to create a schema for items that a user has 'favourited'. My current code, using mongoose and node.js looks at follows:

// load the things we need
var mongoose = require('mongoose');

// define the schema for our favourites model
var favouritedItemsSchema = mongoose.Schema({
    userId           : Number,
    item             : [{
        itemId       : Number,
        addedDate    : Date
    }]
});

// create the model for favourites and expose it to our app
module.exports = mongoose.model('Favourites', favouritedItemsSchema);

Coming from a relational DB background, I am wondering whether the above approach would represent a suitable NoSQL DB design approach? If not, can someone show me what would be something that fits the design philosophy?

Upvotes: 3

Views: 2727

Answers (1)

Odonno
Odonno

Reputation: 419

Yes, you are right, the relational and the NoSQL design approach are totally different.

Where you have 10 tables for example in RDBMS, you could have only 2 or 3 collections in mongo. That's because the way we create relations between objects is far more interesting in NoSQL (subdocument, arrays, etc..).

Here is one solution for your problem, reusing an existing User collection.

// load the things we need
var mongoose = require('mongoose');

// define the schema for our model
var userSchema = mongoose.Schema({
    username: string,
    favourites: [{
        id: Schema.Types.ObjectId,
        addedDate: Date
    }]
});

// export model
module.exports = mongoose.model('User', userSchema);

Upvotes: 4

Related Questions