Refer to population, here extract an example from Mongoose.
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Schema.Types.ObjectId,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
So the example about, Story
model stores related Person._id
in Story._creator
. When you find a document of Story
, you can use populate()
method to define which attribute in Person
model you want to retrieve at the same time, such as:
Story.findOne({_id: 'xxxxxxx'}).populate('person', 'name age').exec(function(err, story) {
console.log('Story title: ', story.title);
console.log('Story creator', story.person.name);
});
I believe this is what you looking for. Or else, you can use nested collections instead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…