【发布时间】:2016-09-11 00:10:11
【问题描述】:
我知道这个问题有 been asked before,但似乎没有一个解决方案适合我。
我有一个这样定义的简单模型:
const mongoose = require('mongoose')
const { Schema } = mongoose
let subscriberSchema = new Schema({
firstName: { type: String, required: true },
email: { type: String, required: true, unique: true }
}, { timestamps: true })
let Subscriber = mongoose.model('Subscriber', subscriberSchema)
如果我运行以下命令(在 REPL 中,因此没有异步问题),我希望看到第二次调用 create 时记录错误。
Subscriber.create({ firstName: "Landon", email: "example@example.com" })
Subscriber.create({ firstName: "Landon", email: "example@example.com" }, function(err) {
console.log("ERROR", err)
})
相反,我看到的是"ERROR" null。
如果我运行count 查询或find 查询,我可以看到两个模型都已创建。我做错了什么?
编辑
以下是我已经尝试过的一些事情:
- 添加索引后重启 MongoDB
- 删除所有现有记录,以便不存在可能违反唯一性约束的现有记录
- 通过所有这些方式定义
email属性(我在不同的地方看到了不同的实现):{ type: String, required: true, unique: true }、{ type: String, required: true, index: true, unique: true }、{ type: String, required: true, index: { unique: true } }。
【问题讨论】:
-
您能否编辑您的问题以包含您通过链接问题检查的内容,这样我们就不必问同样的问题?
-
@JohnnyHK 当然,没问题。已更新。
标签: javascript node.js mongodb mongoose