MongoDB relationships: embed or reference?

后端 未结 11 2574
夕颜
夕颜 2020-11-21 05:34

I\'m new to MongoDB--coming from a relational database background. I want to design a question structure with some comments, but I don\'t know which relationship to use for

11条回答
  •  耶瑟儿~
    2020-11-21 05:53

    Yes, we can use the reference in the document.To populate the another document just like sql i joins.In mongo db they dont have joins to mapping one to many relationship document.Instead that we can use populate to fulfill our scenario..

    var mongoose = require('mongoose')
      , Schema = mongoose.Schema
    
    var personSchema = Schema({
      _id     : Number,
      name    : String,
      age     : Number,
      stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
    });
    
    var storySchema = Schema({
      _creator : { type: Number, ref: 'Person' },
      title    : String,
      fans     : [{ type: Number, ref: 'Person' }]
    });
    

    Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query. Let's look at some examples.

    Better you can get more information please visit :http://mongoosejs.com/docs/populate.html

提交回复
热议问题