2016-10-04 12 views
0

我已經創建了一個名爲'db'的數據庫和一個名爲'Dishes'的集合。我正在使用貓鼬和mongodb。以下是型號代碼和服務器代碼。當我運行服務器時,它顯示盤的名稱是重複的,因此會引發'重複鍵錯誤'的錯誤。我想這是因爲數據庫沒有被丟棄,因此當運行多次時該盤的名稱(根據我的代碼必須是唯一的)不是唯一的。但是,也可能有其他錯誤。請在這裏幫助我。謝謝!db.collection(collection_name).drop()不起作用。創建的數據庫不會被刪除

這是服務器代碼。

var assert=require('assert'); 
var mongoose=require('mongoose'); 

var Dishes=require('./models/dishes1mongoose'); 

var url='mongodb://localhost:27017/conFusion'; 
mongoose.connect(url); 
var db=mongoose.connection; 

db.on('error', console.error.bind(console, 'connection error: ')); 
db.once('open', function(){ 
//connected to the server 
console.log("Connected to the server successfully"); 

    Dishes.create({ 
     name: 'Uthapizza', description: 'I dont know' 
    }, function(err, dish){ 
     if (err) throw err; 
     console.log(dish); 

     var id=dish._id; 

     Dishes.findByIdAndUpdate(id, {$set:{description: 'Updated version of  I still dont know'}}, {new: true}) 
     .exec(function(err, dish){ 
      if (err) throw err; 
      console.log(dish); 

      db.collection("Dishes").drop(function(){ 
       db.close(); 
      }); 
     }); 
    }); 
}); 

這是貓鼬模型的代碼。

var mongoose=require('mongoose'); 

var Schema=mongoose.Schema; 

//create a Schema 
var dishSchema= new Schema({ 
    name : {type: String, required: true, unique: true}, 
    description : {type: String, required: true} 
}, 
{ 
    timestamps: true 
}); 

//create a collection that uses this Schema. It will be of the name that is  plural of the argument "Dish". 
var Dishes=mongoose.model("Dish", dishSchema); 
//make it available elsewhere 
module.exports=Dishes; 
+0

我甚至把「唯一的:假」在型號代碼,避免出現這種情況是暫時的,但它仍然給出了同樣的重複錯誤。我真的很困惑! –

回答

相關問題