简体   繁体   中英

One-To-Many relation in MongoDB

At the moment I am looking at mongoDB. I try to implement a simple one-to-many relation using nodejs and mongoose:

Model/Schema User:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var UserSchema = new Schema({
    name: String
});

module.exports = mongoose.model('User', UserSchema);

Model/Schema Article:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

    var ArticleSchema = new Schema({  
        name: {
            type: String,
            required: true
        },  
        user: {
            type: Schema.ObjectId,
            ref: 'User'
        }   
    });

    module.exports = mongoose.model('Article', ArticleSchema);

So my question, now: How can I get all Users including its Articles? Do I really have to add a ref to my UserScheme, too? What is the best-practice in an one-to-many relation like this? Is there something like a join in mongodb?

One User has many Articles - an Article belongs to one User. Calling something like /user/:user_id , I want to receive the user with _id=user_id containing all of his articles.

That is the most horrible idea, for various reasons.

First, there is a 16MB BSON document size limit. You simply can not put more into a document. Embedding documents is rather suited for "One-to-(VERY-)Few" relationships than for a "One-to-Many".

As for the use case: What is your question here? It is

For a given user, what are the articles?

REST wise, you should only return the articles when /users/:id/articles is GETed and the articles (and only the articles) should be returned as a JSON array.

So, your model seems to be natural. As for the user:

{
  _id: theObjectId,
  username: someString
  …
}

and an article should look like this:

{
  _id: articleIdOrSlugOrWhatever,
  authors: [theObjectId],
  // or author: theObjectId
  retention: someISODate,
  published: someOtherISODate
}

So when your REST service is called for /users/:id you'd simply look up

var user = db.users.findOne({_id:id})

And when /users/:id/articles is called, you'd lookup

var articles = db.articles.find({author:id})

Problem solved in a scalable way, adhering to REST principles.

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