georoot
georoot

Reputation: 3617

Which mongoose model would be more efficient?

I am new to no-sql. I am trying to build a simple e-commerce app in nodejs. Now for the product i need to build CRUD operations so that only owner can edit them, rest have READ-ONLY access. The main question is which would be a better implementation ?

The current code that i have is like

var mongoose = require('mongoose');

module.exports = mongoose.model('product',new mongoose.Schema({
  owner      : {type: String},
  title      : {type: String},
  ...
}));

The owner is actually the _id from my user model. Basically this is something like a foreign key. Is this the valid method to go around or should i add an array inside the user model to store the list of objects that he owns ?

Also i would like to have validation if what i just did for owner, storing UID in String is best practice or should i do something else to reference the user model.

Thanks in advance for helping me out.

Upvotes: 0

Views: 157

Answers (1)

Soviut
Soviut

Reputation: 91714

The whole point of document databases is you shouldn't have foreign relationships; All the data your document needs should be denormalized in the document.

So inside your product document, you should be duplicating all the owner details you need. You can store their _id as well for lookup, but don't use a string for this, use an actual ObjectId().

For more about denormalization see The Little MongoDB Book

Yet another alternative to using joins is to denormalize your data. Historically, denormalization was reserved for performance-sensitive code, or when data should be snapshotted (like in an audit log). However, with the ever- growing popularity of NoSQL, many of which don’t have joins, denormalization as part of normal modeling is becoming increasingly common. This doesn’t mean you should duplicate every piece of information in every document. However, rather than letting fear of duplicate data drive your design decisions, consider modeling your data based on what information belongs to what document.

Upvotes: 1

Related Questions