1

I have a .json file on my hard drive with about 70 entries.

This is the model i'm using:

var tweetModel = mongoose.model('tweet', {
    "correct":Boolean,
    "text": String,
    "id":{type:String, unique:true},
    "user":{
        "atNamn":String,
        "namn":String,
        "bild":String,
        "id":String
}
});

Some of the tweets are duplicates and therefore share the same "id" attribute. I want to filter these out when adding. At the moment i just go through the JSON like this.

var JSONData = require("../public/data/jsondata")
for(key in JSONData){
    new tweetModel(JSONData[key]).save(function(err,doc){
        if(err){console.log(err)}
        else{
            console.log(doc);
        }
    })
}

If i run this one time, they ALL get added. If i do it one more time a duplicate error is thrown. I want it to check for duplicates BEFORE adding!

Max Krog
  • 181
  • 1
  • 2
  • 11

1 Answers1

1

Use a simple JS object to keep track of which id values you've already seen:

var seenIds = {};
for(key in JSONData){
    var json = JSONData[key];
    if (!seenIds[json.id]) {
        seenIds[json.id] = true;
        new tweetModel(json).save(function(err,doc){
            if(err){console.log(err)}
            else{
                console.log(doc);
            }
        });
    }
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471