1

I'm sure to be missing something obvious here. My understanding was that the code below should throw an 11000 Duplicate Key Error, but it just adds both users to the database, and doesn't throw any errors. Anyone have any ideas how to make the email unique? db version v2.4.5.

var mongoose = require('mongoose')
, Schema = mongoose.Schema;

mongoose.connect("mongodb://localhost/db");

var User = mongoose.model('User', new Schema({
    email: {type: String, index: true, unique: true}
}));

new User({
    email: "a@duplicate.com"
}).save(function(err,user){
    console.log(err);
});

new User({
    email: "a@duplicate.com"
}).save(function(err,user){
    console.log(err);
});

Edit

I seem to get it to work by going to the mongo command line, and typing:

db.users.ensureIndex({email:1},{unique:true});

The node script then works fine as expected and throws the errors. However, I am not sure why this isn't working through Mongoose. The output from mongoose debug is:

Mongoose: users.ensureIndex({ email: 1 }) { safe: undefined, background: true, unique: true }
Mongoose: users.insert({ __v: 0, _id: ObjectId("51fb961445cf690000000001"), email: 'a@duplicate.com' }) {}
Mongoose: users.insert({ __v: 0, _id: ObjectId("51fb961445cf690000000002"), email: 'a@duplicate.com' }) {}
Err=null
Err=null

I notice that ensureIndex line in the output fails if I execute it manually.

4

1 回答 1

0

我的猜测是你的索引没有粘住,你后来修复了语法。

db.users.getIndexes()

下次使用它来验证集合上是否有索引。

于 2013-08-02T12:49:25.640 回答