为什么在猫鼬填充示例中使用ObjectId和Number? [英] Why do they use an ObjectId and a Number in the Mongoose Population example?

查看:95
本文介绍了为什么在猫鼬填充示例中使用ObjectId和Number?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例中,他们使用ObjectId引用这我明白.但是在storySchema中,为什么他们不这样做来引用此人呢?

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?

反之:为什么使用ObjectId而不是Person in Number?

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

推荐答案

引用的类型必须与引用的架构的_id属性相同.

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

如果是personSchema,则为Number.

storySchema具有由猫鼬自动分配的_id字段-在架构构造函数的参数中未指定.

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

如果没有将Mongoose传递给Schema构造函数,则默认情况下,Mongoose将为每个Schema分配一个_id字段.辅助类型是与MongoDB的默认行为一致的ObjectId

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

这篇关于为什么在猫鼬填充示例中使用ObjectId和Number?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆