1

Db creation:

var mongojs = require('mongojs');
var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']);

i'm trying to do a search in database with this code, using findOne from mongojs, that is the code:

app.get('/detalhesContato/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.contatos.findOne({_id: mongojs.ObjectId(id)}, function(err, doc)    {
 console.log(err);
  res.json(doc);

});

console.log(id) the id is correct but findOne is not working no matter what i do ;(.

"567a16ba28dee028f4a8ad78 <-- console log from id

TypeError: Cannot read property 'findOne' of undefined at /Users/Michel/Documents/AngularProjects/RodrigoBranasListaTelefonica/server.js:48:12"

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
michelpm1
  • 177
  • 1
  • 1
  • 12

2 Answers2

0

With mongojs, you need to explicitly identify the collections you want to access as properties of db when you call mongojs to create your db object. So because you're trying to access the contatos collection, that name needs to be provided to your mongojs call in the second (array of strings) parameter:

var db = mongojs('rodrigo-contatos', ['contatos']);

Or you can just skip the short-cut access from db and get the collection later:

var contatos = db.collection('contatos');
contatos.findOne(...);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • humm it's impossible to maintain connection with all the database at once? – michelpm1 Feb 05 '16 at 20:51
  • this code works anyway without identifying: db.collection('contatos').find(function(err, docs){ console.log(docs); res.json(docs); }); – michelpm1 Feb 05 '16 at 20:53
0

Ok problem solved you need to identify collection when creating db connection. Interesting that was only necessary for findOne() with find() was working just fine this way:

var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']); 

but like this, work like charm with findOne():

 var db = mongojs('rodrigo-contatos', ['contatos']);
michelpm1
  • 177
  • 1
  • 1
  • 12