如何在mongoose中将ObjectId设置为数据类型

ido*_*hir 52 mongoose node.js

在mongoHQ和mongoose上使用node.js,mongodb.我正在为类别设置架构.我想使用文档ObjectId作为我的categoryId.

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
    categoryId  : ObjectId,
    title       : String,
    sortIndex   : String
});
Run Code Online (Sandbox Code Playgroud)

然后我跑了

var Category = mongoose.model('Schema_Category');
var category = new Category();
category.title = "Bicycles";
category.sortIndex = "3";

category.save(function(err) {
  if (err) { throw err; }
  console.log('saved');
  mongoose.disconnect();     
});
Run Code Online (Sandbox Code Playgroud)

请注意,我没有为categoryId提供值.我假设mongoose将使用模式生成它,但文档具有通常的"_id"而不是"categoryId".我究竟做错了什么?

add*_*onj 104

与传统的RBDM不同,mongoDB不允许您将任何随机字段定义为主键,所有标准文档都必须存在_id字段.

因此,创建单独的uuid字段没有意义.

在mongoose中,ObjectId类型不用于创建新的uuid,而是主要用于引用其他文档.

这是一个例子:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
    categoryId  : ObjectId, // a product references a category _id with type ObjectId
    title       : String,
    price       : Number
});
Run Code Online (Sandbox Code Playgroud)

如您所见,使用ObjectId填充categoryId没有多大意义.

但是,如果您确实需要一个名称很好的uuid字段,mongoose会提供允许您代理(引用)字段的虚拟属性.

看看这个:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
    title       : String,
    sortIndex   : String
});

Schema_Category.virtual('categoryId').get(function() {
    return this._id;
});
Run Code Online (Sandbox Code Playgroud)

所以现在,只要你调用category.categoryId,mongoose就会返回_id.

您还可以创建"设置"方法,以便设置虚拟属性,查看此链接 以获取更多信息


jpe*_*nna 24

我正在寻找问题标题的不同答案,所以也许其他人也会这样.

要将类型设置为ObjectId(例如,您可以引用author作为作者book),您可能会这样做:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});
Run Code Online (Sandbox Code Playgroud)