Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使模式设计中的字段具有唯一性。(RESTful API)_Node.js_Mongodb_Rest - Fatal编程技术网

Node.js 使模式设计中的字段具有唯一性。(RESTful API)

Node.js 使模式设计中的字段具有唯一性。(RESTful API),node.js,mongodb,rest,Node.js,Mongodb,Rest,我正在为任务管理实现一个API,它有两个端点用户和任务。“用户”的架构设计如下所示: // Define our user schema var userSchema = new mongoose.Schema({ name: { type:String, required: true }, email: { type: String, required: true }, pending

我正在为任务管理实现一个API,它有两个端点用户和任务。“用户”的架构设计如下所示:

// Define our user schema
var userSchema = new mongoose.Schema({
    name: { 
        type:String,
        required: true
    },

    email: {
        type: String,
        required: true
    },

    pendingTasks: [String],

    dateCreated: { 
        type: Date, 
        default: Date.now }
});

我的问题是,如何使每个数据的电子邮件都是唯一的?(不允许多个用户使用同一封电子邮件)

据我所知,您的收藏中不允许重复电子邮件,对吗

归档的一种方法是将
唯一索引
定义添加到
电子邮件
属性。像这样:

// Define our user schema
var userSchema = new mongoose.Schema({
    name: { 
        type:String,
        required: true
    },

    email: {
        type: String,
        required: true,
        index: true,  // NEW Added!
        unique: true  // NEW Added!
    },

    pendingTasks: [String],

    dateCreated: { 
        type: Date, 
        default: Date.now }
});
请记住重新启动您的mongoose(我认为您可以通过重新启动Node.js应用程序来完成)。默认情况下,mongoose将在启动时创建索引

如果要确认要创建的索引,请登录mongodb控制台并使用:
db.users.getIndexes()
进行检查

参考:
  • 如何通过mongoose定义索引:
  • Mongodb官方指南:

  • 也许是l。一个简单的搜索或者也会引导你找到大量的相关信息。谢谢,这是一个很好的答案。您还可以看看我关于创建RESTful API的不同问题吗@Dawn17,不客气,你可以看到我对这个问题的建议:)