0

I have created a database by the name 'db' and a collection by the name 'Dishes'. I am using mongoose and mongodb. Below are the model code and the server code. When I run the server, it shows that the name of the dish is repeated, and hence throws an error of 'duplicate key error'. I suppose this is because the database has not been dropped and hence the name of the dish (which must be unique as per my code) is not unique when run more than once. However, there may be a different error too. Kindly help me out here. Thanks!

This is the server code.

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();
            });
        });
    });
});

This is the code for the mongoose model.

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;
Community
  • 1
  • 1
SHIVANG AGARWAL
  • 53
  • 1
  • 10
  • I even put the 'unique: false' in the model code, to avoid this situation temporarily, but it still gives the same duplication error. I am really confused here! – SHIVANG AGARWAL Oct 04 '16 at 16:19

1 Answers1

0

Try to use the following:

mongoose.connection.collections['Dishes'].drop(cb)

https://stackoverflow.com/a/10088410/4442630

Community
  • 1
  • 1