Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I'm basically working on designing a database structure for a new project, and I'm a pretty noob to MongoDB and Mongoose.

I've read some Mongooses population paper, where it has a one-to-many relationship, with one Person document to many Story documents, but the part that puzzles me is where instead of the Story documents referencing what Person document it belongs to, the Person schema has it set up so it has an array of what Story documents it 'owns'.

I'm setting up something very similar to this. But I keep thinking it would be easier when creating new Story documents to have the Person document ID. But maybe that's just because I'm more familiar with MySQL relationships using joins.

What's the best way to update the array of stories in the associated People document it belongs to? 

I'm sure this is an easy solution that I just overlooked or something, but any help would be great. Thanks!

1 Answer

0 votes
by (108k points)

Here is an example of Mongoose. I believe this is what you looking for:

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 in the example, Story model stores related Person._id in Story._creator. When you look for 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);

});

Related questions

Browse Categories

...