ericbae
ericbae

Reputation: 9644

NodeJS, Mongoose - Duplicate entries when inserting data

I have NodeJS with Mongoose and I'm accessing an API to retrieve data. I have a Schema as follows.

var dataSchema = new Schema({
  id:Number,
  name:String
));

And I'm using the following code to insert.

  var d = Data.find({id:data.id}, function(error, curr_data) {
    if(curr_data.length == 0) { // check to make sure only unique entries are entered
      console.log("      Inserting : " + curr_data.name);
      new Data(data).save();
    }
  });

But when I check my Mongo DB, I can still see duplicate entries.

Is there anther way?

Upvotes: 1

Views: 3952

Answers (2)

THE ONLY ONE
THE ONLY ONE

Reputation: 2190

You can use Mongo's built-in count() method to check if the row exists and from that conditionally save the model:

Data.count({id: data.id}, function (err, count) {
  if (!count) {
    console.log("Inserting " + curr_data.name);
    new Data(data).save();
  }
  else {
    // Handle err.
    console.log('Already Exists');
  }
});

Upvotes: 2

Brett
Brett

Reputation: 3885

You do not need to add an id to your schema, Mongoose creates an ObjectId for you.

"Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assiged is an ObjectId to coincide with MongoDBs default behavior. If you don't want an _id added to your schema at all, you may disable it using this option." - From the Mongoose docs

If you do want to specify your own id you can do the following to ensure that no duplicates are created:

var dataSchema = new Schema({
  id: {
    type: Number,
    index: {
      unique: true
    }
  },
  name: String
},
{ _id: false });

Upvotes: -1

Related Questions