2012-01-26 94 views
19

我想讓關鍵項目在該集合中唯一,但我不能得到這個工作,我在這裏發現類似的問題。Mongoose與模式密鑰重複唯一

task.js

function make(Schema, mongoose) { 

    var Tasks = new Schema({ 
     project: { type: String, index: { unique: true, dropDups: true }}, 
     description: String 
    }); 

    mongoose.model('Task', Tasks); 
} 
module.exports.make = make; 

test.js

var mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost/rss'); 

var Schema = mongoose.Schema 
    , ObjectId = Schema.ObjectId; 

require('./task.js').make(Schema, mongoose); 
var Task = mongoose.model('Task'); 
var newTask = new Task({ 
    project: 'Starting new project' 
    , description: 'New project in node' 
}); 
newTask.save(function(err) { 
    if (err) console.log('Error on saving'); 
}); 

mongoose.disconnect(); 

當運行與節點test.js該應用程序,仍然產生重複。

MongoDB shell version: 2.0.2 
connecting to: rss 
> db.tasks.find() 
> db.tasks.find() 
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa3d48d4e1533000001") } 
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa4d9a8921a33000001") } 
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa57ebeea1f33000001") } 

//編輯還是同樣的問題,這裏就是我試圖做 刪除db.tasks.drop()集合 重啓蒙戈須藤停止的MongoDB,並開始MongoDB的,再試,還是運行程序同樣的問題,它如何允許索引上的重複數據?

回答

22

你傳遞,因爲你築巢「獨一無二」的屬性爲「索引」屬性,嘗試這樣的事情(它按預期工作)可能無法正常工作架構對象:

User = mongoose.model('User', new Schema({ 
    firstName: { 
     type:String, 
     required: true, 
    }, 
    lastName: { 
     type:String, 
     required: true, 
    }, 
    email: { 
     type:String, 
     required: true, 
     unique: true 
    }, 
    address: String, 
    phone: { 
     type:String, 
     required: true, 
    }, 
    password: { 
     type:String, 
     required: true, 
     set: Data.prototype.saltySha1 // some function called before saving the data 
    }, 
    role: String 
},{strict: true})); 

或者更具體地說您例如:

var Tasks = new Schema({ 
    project: { 
     type: String, 
     unique: true, 
     index: true 
    }, 
    description: String 
}); 

注:我不知道你想用「dropDups」參數做什麼,它不會似乎是在mongoose documentation

+6

dropDups來自mongodb-native – jackdbernier

+1

dropDups從2.6版棄用https://docs.mongodb.com/v2.6/tutorial/create-a-unique-index/#drop-duplicates –