如何在 mongoose 中将 ObjectId 设置为数据类型 [英] How to set ObjectId as a data type in mongoose
问题描述
在 mongoHQ 和 mongoose 上使用 node.js、mongodb.我正在为类别设置架构.我想使用文档 ObjectId 作为我的 categoryId.
Using node.js, mongodb on mongoHQ and mongoose. I'm setting a schema for Categories. I would like to use the document ObjectId as my categoryId.
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
categoryId : ObjectId,
title : String,
sortIndex : String
});
然后我跑
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();
});
请注意,我没有为 categoryId 提供值.我假设 mongoose 将使用模式来生成它,但文档具有通常的_id"而不是categoryId".我做错了什么?
Notice that I don't provide a value for categoryId. I assumed mongoose will use the schema to generate it but the document has the usual "_id" and not "categoryId". What am I doing wrong?
推荐答案
与传统的 RBDM 不同,mongoDB 不允许您定义任何随机字段作为主键,所有标准文档都必须存在 _id 字段.
Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.
因此,创建单独的 uuid 字段没有意义.
For this reason, it doesn't make sense to create a separate uuid field.
在 mongoose 中,ObjectId 类型不用于创建新的 uuid,而是主要用于引用其他文档.
In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.
这是一个例子:
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
});
如您所见,使用 ObjectId 填充 categoryId 没有多大意义.
As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.
但是,如果您确实想要一个命名良好的 uuid 字段,mongoose 提供了允许您代理(引用)字段的虚拟属性.
However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.
检查一下:
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;
});
所以现在,每当您调用 category.categoryId 时,mongoose 只会返回 _id.
So now, whenever you call category.categoryId, mongoose just returns the _id instead.
您还可以创建一个set"方法,以便您可以设置虚拟属性,请查看此链接了解更多信息
You can also create a "set" method so that you can set virtual properties, check out this link for more info
这篇关于如何在 mongoose 中将 ObjectId 设置为数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!