1

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?

2 Answers 2

2

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');
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

You can use the exact same thing with .findOne too, which is slightly less memorable but does offer you the full returned db row that you can access properties on if it is a duplicate.
-1

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

1 Comment

[Error: document must have an _id before saving]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.