2

In this example, they create personSchema using ObjectId to reference the Story and this I understand. But then in storySchema why don't they do the same to reference the person?

Or the inverse: why using ObjectId instead of Number in Person?

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' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
fusio
  • 3,595
  • 6
  • 33
  • 47

1 Answers1

3

Type of reference has to be the same as the referenced schema's _id property.

In case of personSchema it's a Number.

storySchema on the other hand, has the _id field assigned automatically by mongoose - it's not specified in parameters for the schema constructor.

Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assiged is an ObjectId to coincide with MongoDBs default behavior

soulcheck
  • 36,297
  • 6
  • 91
  • 90
  • so if they did not specify the `_id` in `personSchema` they could have used `ObjectId` in `_creator` and `fans`? is there a particular reason why they preferred using a Number? – fusio Aug 13 '13 at 13:20
  • @fusio maybe they wanted to avoid the chicken-egg situation by setting their own id on one of the collections - that way they don't have to wait until mongo inserts the document to reference it from another. That way you only need books inserted before setting up the references. Can't say for sure though. – soulcheck Aug 13 '13 at 13:29
  • 1
    They probably just did it so that it shows the example in case someone ever does change the _id. You can reference the _id without saving an object. – dansch Nov 16 '13 at 20:58
  • You're not alone - that Mongoose example confused me too (3 hours of searching later.) A clearer example would have been to return the newly saved `person` doc (assigned to the `aaron` variable) then reference the newly generated `_id` that way, which would have meant that the `personSchema._id` field could have been handled by Mongo rather than set manually. Does this sound logical or am I barking up the wrong tree here? – I am me May 24 '17 at 08:55