首页 > 解决方案 > 无法在 Mongo 模式中生成 uuid

问题描述

我正在尝试使用以下代码在我的 Mongodb 4.x 架构中创建一个 id,但我收到一条错误消息,提示未定义 uuid。

_id: { type: String, default: function genUUID() {
    uuid.v1()
}}

这看起来像我做的一切都是正确的。

我能错过什么?

我想一个后续问题是,您将如何为架构中的单个值字段自动生成 _id。

例子:

var ProfileSchema = new Schema({
highschool:{
  item: { type: String },
  _id: { type: String, default: uuid.v4}
},
college:{
  item: { type: String },
  _id: { type: String, default: uuid.v4}
});


var ProfileSchemaIds = new Schema({
   highschool: { type: Schema.Types.ObjectId, ref: 'ProfileSchema.Highschool' },
   college: { type: Schema.Types.ObjectId, ref: 'ProfileSchema.College' }
   // ... rest of your schema props
});

标签: mongodbmongoose

解决方案


看来您真正需要的是 3 个模型之间的引用,其中Profile将引用HighSchoolSchema 和CollegeSchema,如下所示:

var ProfileSchema = new Schema({
   highschool: { type: Schema.Types.ObjectId, ref: 'Highschool' },
   college: { type: Schema.Types.ObjectId, ref: 'College' }
   // ... rest of your schema props
});

Highschool并且College将是单独的模式等。

更多信息mongoose populate etc


推荐阅读