0

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

Community
  • 1
  • 1
Howe Chen
  • 143
  • 2
  • 12

1 Answers1

2

db.collection.find only works if you are using the mongo shell. what you're after is mongoose queries, since you tagged mongoose I shall assume you've set it up.

Assuming that your model name is twitterIAlreadyStored

and the property you are looking in id_str

the value you're trying to find is newTweet.id_str

this would be the format to follow:

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;
  }
};

express.js doc on res.send() and res.end()

Ta946
  • 1,342
  • 12
  • 19
  • Thank you very much, your answer solve my question with some editings.. – Howe Chen Apr 06 '16 at 14:41
  • i just provide the model name like this as my model is in models dir: const users = require('../models/users.models');, but its not working, err: MissingSchemaError: Schema hasn't been registered for model "model". – Zombie Oct 04 '18 at 15:10