Mongoose : don't insert if element already stored

前端 未结 1 649
时光说笑
时光说笑 2021-02-13 05:11

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

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 06:05

    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.

    0 讨论(0)
提交回复
热议问题