Mongoose : don't insert if element already stored

express, mongodb, mongoose

Solution

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.

Problem

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

Original source