【发布时间】:2011-08-21 05:33:06
【问题描述】:
我在使用 Mongoose / MongoDb 创建唯一索引时遇到问题,无法让它工作。设置唯一索引后,我可以添加两个具有相同属性值的文档。
我已经尝试了所有我能想到的 - 重新启动(一切)更改语法等。
代码
添加>>这是我用来保存实体的方法:
create : function(entity, definition, successFn, errorFn){
var model = mongoose.model(entity);
newModel = new model(definition);
newModel.save(function(error) {
if(error){
if(!errorFn){
throw error;
}
errorFn(newModel);
return;
}
successFn(newModel);
});
}...
var Something = new Schema({
objectId : ObjectId,
name : { type : String, index: { unique: true }},
url : { type : String, index: { unique: true }},
...etc
mongoose.model('Something', Something);
Mongo 输出
[conn1] insert xxxxx.agencies 1526ms
[conn1] building new index on { name: 1 } for xxxxx.agencies
[conn1] insert xxxxx.system.indexes exception 11000 E11000 duplicate key error index: xxxxx.agencies.$name_1 dup key: { : "something" } 4ms
[conn1] building new index on { url: 1 } for xxxxx.agencies
[conn1] insert xxxxx.system.indexes exception 11000 E11000 duplicate key error index: xxxxx.agencies.$url_1 dup key: { : "http://www.something.com" } 1ms
当我签入 MongoHub 时,索引没有出现,所以它们看起来不像是创建的。
这是this question 的副本,但它没有适合我的答案。
【问题讨论】:
标签: javascript mongodb node.js mongoose