Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose : don't insert if element already stored

I'm using MongoDB and Mongoose with Express to store tweets that I retrieve via the Twitter API.

I want to avoid saving duplicate tweets. I am doing something like that :

TweetsModel.find({tweet_id: tweet.tweet_id}, function (err, tweets) {
    if(tweets.length > 0){
        cb('Tweet already exists',null);
    } else{
        tweet.save(function(err){
            cb(err,user);
        });
    }
});

My question is : for performance reason, is there a way using Mongoose to avoid doing two requests ? One find and one save ?

Knowing that I don't want to update the tweet if it already exists either.

Thank you

like image 704
tomahim Avatar asked Dec 01 '13 12:12

tomahim


1 Answers

You can use an update call with the upsert option to do this:

TweetsModel.update(
    {tweet_id: tweet.tweet_id}, 
    {$setOnInsert: tweet}, 
    {upsert: true}, 
    function(err, numAffected) { .. }
);

If a doc already exists with that tweet id, then this is a no-op. Otherwise it will add the doc.

$setOnInsert requires v2.4+ of MongoDB. If your version is less than 2.4, things get more complicated.

like image 99
JohnnyHK Avatar answered Sep 18 '22 13:09

JohnnyHK