简体   繁体   中英

Node js + Mongo db design

I'm developing a node.js + mongoose webapp, and I have one doubt about database creation. This is how database is defined:

var user = new Schema({
 id : ObjectId,
 name : String,
 password : String,
 email : String,
 created : Date
});
var comment = new Schema({
 id : ObjectId,
 userId: ObjectId,
 content : String,
 created : Date
})

I want to link each comment with its user... So... which is the best way to do this? I thought to add one of these two to the comment Schema... but I don't know if its the correct answer or if there's another better:

userId: ObjectId,

or:

userObject: user

Thanks!

Hope you can help me!

Well, it depends. There is no definitive answer to your question. Generally, I'd advise you not to use native MongoDB field references, which come with a slight size overhead.

For all of my projects, I would definitely choose the first solution, which is generally much more flexible and which will save you some disk space. At the cose of having to do one more request by yourself.

The simple data structure for this case is using what mongoose calls embedded documents .

As Brandon Tilley mentioned, you might also want to take a look at DBRef-like behavior and populate functionality of mongoose . This would allow you to handle your Comments entity as a separate, independent entity. The downside is that if you have a comment's instance and want to access the user's attributes, you have to populate your reference to the user first.

In the end, it depends on your use case and how you'd rather navigate your info. I say don't think too much about it and try any. If you decide later that another structure works best, just change it. Fortunately, this is very simple with MongoDB and NoSQL in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM