How to test if a value exists?

时间:2016-04-04 19:02:33

标签: node.js mongodb mongoose database

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??

1 个答案:

答案 0 :(得分:2)

db.collection.find仅在您使用mongo shell时才有效。 你所追求的是mongoose次查询,因为你标记了mongoose我会假设你已经设置了它。

假设您的model名称为twitterIAlreadyStored

以及property

中的id_str

您要查找的valuenewTweet.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