Mongoose:如果元素已经存储,请勿插入 [英] Mongoose : don't insert if element already stored
问题描述
我想避免保存重复的tweets。我正在做这样的事情:
TweetsModel.find({tweet_id:tweet.tweet_id}函数(err,tweets){
if(tweets.length> 0){
cb('Tweet already exists',null);
} else {
tweet.save (function(err){
cb(err,user);
});
}
});
我的问题是:出于性能原因,是否有一种方式使用Mongoose避免做两个请求?一个找到一个保存?
知道我不想更新推文,如果它已经存在。
谢谢
您可以使用更新
调用上传选项来执行此操作:
TweetsModel.update(
{tweet_id:tweet.tweet_id},
{$ setOnInsert:tweet},
{upsert:true},
函数(err,numAffected){..}
);
如果一个文档已经存在该tweet id,那么这是一个no-op。否则将添加文档。
$ setOnInsert
需要MongoDB的v2.4 +。如果您的版本小于2.4,则会更复杂。
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
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.
这篇关于Mongoose:如果元素已经存储,请勿插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!