Why do they use an ObjectId and a Number in the Mongoose Population example?

独自空忆成欢 提交于 2019-12-02 01:42:39

问题


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);

回答1:


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



来源:https://stackoverflow.com/questions/18209964/why-do-they-use-an-objectid-and-a-number-in-the-mongoose-population-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!