如何使变量成为猫鼬的唯一键? [英] how to make a variable a unique key in mongoose?

查看:64
本文介绍了如何使变量成为猫鼬的唯一键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有此架构

var userSchema = mongoose.Schema({
    username: String,
    email: String,
    password: String,
    _todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});

我希望用户名是唯一密钥,其他用户不能重复.我该怎么办?

I would like the username to be a unique key that cannot be duplicated by other users. How can I do this?

推荐答案

您可以使用unique属性添加约束.这还将为该字段添加一个唯一"索引到您的集合:

You can add a constraint with the unique attribute. This will also add a "unique" index for the field to your collection:

var userSchema = mongoose.Schema({
    username: { type: String, unique: true },
    email: String,
    password: String,
    _todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});

这篇关于如何使变量成为猫鼬的唯一键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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