如何在mongoDB中创建唯一索引?
处理帐户的服务具有添加新帐户的路径。显然,帐户中的电子邮件字段应该是唯一的。我希望应用程序在匹配成立时随时抛出错误。
此时它通过手动功能实现:
const { createError } = require('micro')
const createAccount = async (collection, credentials) => {
const { email } = credentials
const account = await collection.findOne({ email })
if (account) {
throw createError(401, 'this email is already used')
}
collection.insertOne({ email })
}
module.exports = createAccount
当我使用mongoose时,添加唯一索引没有问题。这次,使用了原生的mongoDB驱动程序。根据文档,我试图添加如下内容:
collection.createIndex({ email: 1 }, { unique: true })
事实上,它确实创建了一个索引,我可以在我的mlab主页中看到它:
也许我使用了过时的语法或类似的东西?为什么key的唯一设置为false?
回答如下:你有使用ensureIndex
collection.ensureIndex(option, response){
// here call you fucntion
}
ensureIndex方法将创建索引(如果尚未存在)。