猫鼬:是否需要将自定义_id声明为索引并且是唯一的 [英] Mongoose: does a custom _id need to be declared as an index and be unique

查看:32
本文介绍了猫鼬:是否需要将自定义_id声明为索引并且是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用猫鼬定义集合结构的常用方法:

Here is the common way to define a collection structure with Mongoose :

var UserSchema = new Schema({
    _id: Schema.Types.ObjectId,
    username: String,
    ...
});

现在我想将_id字段声明为Number类型:

And Now I want _id field declared as Number type :

var UserSchema = new Schema({
    _id: Number,
    username: String,
    ...
});

问题是,我需要声明有关_id的更多信息吗?如:

The problem is, do I need to declare more infomation about _id ? Such as :

var UserSchema = new Schema({
    _id: {type: Number, required: true, index: {unique: true}},
    username: String,
    ...
});

我不确定MongoDB是否会自动执行.

I am not sure whether MongoDB would do it automatically.

推荐答案

好吧,经过一些实践,我意识到MongoDB会自动将_id设置为PRIMARY KEY(NOT NULL + UNIQUE INDEX).因此,只需键入:

Well, after some practice, I realized that, MongoDB would set _id as PRIMARY KEY (NOT NULL + UNIQUE INDEX) automatically. So, just type:

_id: Number,
...

这篇关于猫鼬:是否需要将自定义_id声明为索引并且是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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