I am using mongodb to build an app which get the user's twitter timeline in a mongodb database, I want to check if the tweets I got from twitter has already existed in my database, so I use the mongodb.find()
function.
The whole function is like this:
db.collection.find({'twitterIAlreadyStored.id_str': newTweet.id_str}
Then I want to write a logical code which is:
if(exist){
} else {
}
So I am wondering if there is any way to test if the result of find exists or not??
答案 0 :(得分:2)
db.collection.find
仅在您使用mongo shell
时才有效。
你所追求的是mongoose次查询,因为你标记了mongoose
我会假设你已经设置了它。
假设您的model
名称为twitterIAlreadyStored
以及property
id_str
您要查找的value
是newTweet.id_str
这将是以下格式:
var mongoose = require('mongoose');
mongoose.model('MODELNAME').findOne({'PROPERTY': 'VALUE'}, function(error, exist) {
if(exist && !error){
//do something
} else {
//IF YOU ARE USING EXPRESS.JS, YOU MUST USE RES.SEND() or RES.END() TO TERMINATE THE CONNECTION
res.status(500).send({"message" : "Not Found"});
return;
}
};
res.send()和res.end()上的express.js doc