简体   繁体   English

在mongoose中使用uuid作为objectID

[英]using uuid as objectID in mongoose

How can i use an UUID generated string, instead of the original mongoose ObjectID string , keeping the objectID methods(ValueOf(), To String(), ....) ? 我如何使用UUID生成的字符串,而不是原始的mongoose ObjectID字符串,保留objectID方法(ValueOf(),To String(),....)?

when i generate UUID and i try to use in my mongoose schema with 当我生成UUID并尝试在我的mongoose模式中使用

in my model: 在我的模型中:

var uniqueUUID = uuid.v4();
createUser = user({
            'myid': uniqueUUID,
});

in my model/schema: 在我的模型/架构中:

var userSchema = new mongoose.Schema({

_id: Schema.Types.ObjectId

});

got a validation error. 得到验证错误。

ValidationError: user validation failed

You are trying to add a key that doesn't exist in the schema. 您正在尝试添加架构中不存在的密钥。 There is no myid key defined in your schema. 您的架构中没有定义myid键。 By default mongoose doesn't allow keys that haven't been pre-defined. 默认情况下,mongoose不允许未预定义的密钥。

You can change it up to be something like this: 您可以将其更改为以下内容:

var userSchema = new mongoose.Schema({

_id: {type: String, default: uuid.v4}

});

That automaticly assings the object id with the generated uuid.v4 value. 这会自动使用生成的uuid.v4值来确定对象id。

When creating user use: 创建用户使用时:

var newUser = new user();

That has automaticly assigned the id for the document. 这已自动为文档分配了id。 Just remeber to save it. 请记住保存它。 :) :)

If you want to have another id field called myid you can add that to the schema by following how the _id has been added. 如果您想要另一个名为myid id字段,可以按照如何添加_id将其添加到模式中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM