Mongodb in node.js - node.js

I'm trying to get my app to return something from the mongodb server its connected to but every time it returns :
{col :
{manager:
{driver:[object],
helper:[object],
.
.
.
query{}}
in my app.js i wrote :
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Messages');
var collection = db.get('msgCollection');
var a= collection.find({});
console.log(a);
I checked and the database and collection exist. If i write in the mongo console db.msgCollection.find() it works
Any one knows what the problem ?
Thank you!

Monk's API is asynchronous (as is most of nodejs api).
To get results from query, You have to:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/Messages');
var collection = db.get('msgCollection');
collection.find({}, function(err, data) {
//handle error
console.log(data);
});
Or use promises.

Related

Accessing MongoDB Documents Properties in ExpressJS App

I have the following code and I am trying to fetch documents from the MongoDb database and display the first name property of each document. For some reason I get the following error:
TypeError: Cannot read property 'firstName' of undefined
Here is my app.js implementation:
const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var db = {}
var url = 'mongodb://localhost:27017/bank';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
this.db = db;
console.log("Connected correctly to server.");
db.close();
});
app.get('/customers',function(req,res){
console.log("customers")
this.db.open()
var documents = this.db.collection("customers").find()
documents[0].firstName // how to access the first name property
this.db.close()
res.send("fetching customers")
})
What can i see in code is this.
you have a global scope variable .
var db = {};
and then you are doing
MongoClient.connect(url, function(err, db) {
do staff
when you do
db.close(); the client is close;
})
and when you are opening the this.db.open(); next time the connection is close for mongoclient.
either don't do db.close() or
create mongoclient when you do query

MongoJS returns no results while MongoClient does

I am trying to connect to MongoDB with Node.js. MongoClient works fine, but Mongojs doesn't:
var MongoClient = require('mongodb').MongoClient;
var mongojs = require('mongojs');
var url = '...';
MongoClient.connect(url, function(err, client) {
var cursor = client.db("events").collection('events').find();
cursor.each(function(err, event) {
console.log("OK MONGODB");
});
});
mongojs(url, ['events']).events.find(function(err, events) {
events.forEach(function(event) {
console.log("OK MONGOJS");
});
});
"OK MONGODB" is logged several times; "OK MONGOJS" is not.
What's wrong, please?
In your case, the url used in MongoClient should be different with mognojs.
Suppose the url is 'mongodb://localhost/', it is OK for MongoClient. However, the url used in mongojs should be added with dbname as following
var db = mongojs('mongodb://localhost/mydb', ['mycollection']);
So it should be as below
mongojs(url+'events', ['events']).events.find(...);

TypeError: Object #<MongoClient> has no method 'db' solution vs Documentation

While going through a mongodb tutorial, I ran into an issue with this configuration:
var MongoClient = require('mongodb').MongoClient;
var mongoClient = new MongoClient(new server('localhost', '27017', {'native_parser': true}))
var db = mongoClient.db('test');
TypeError: Object # has no method 'db'
Eventually, I was able to solve it using mongodb server
var server = require('mongodb').Server,
Db = require('mongodb').Db;
var db =new Db('test', new server('localhost', '27017', {'native_parser': true}));
db.open(function(err, res){
app.listen(8080);
console.dir('app started on 8080');
});
However, the documentation says "Server should not be used, use the MongoClient.connect."
Based on this, I'd like to know when is the appropriate time to use the server?
Here is an example on how to use it in regards to the deprecation present in 2.0 and your setup and usage of callbacks instead of promises:
var mongoDB = require('mongodb');
var theDB = null;
mongoDB
.MongoClient
.connect('mongodb://localhost:27017/test', null, function(err, db) {
if (err) {
console.error(err);
} else {
theDB = db;
app.listen(8080);
console.dir('app started on 8080');
}
});

node.js / mongodb file structure

I'm trying to set up this simnple NodeJS/mongodb app and I have my files structured like this:
server.js
|
+-routes/menu.js
+-routes/cases.js
In my server.js I declare my mongodb vars like this:
var express = require('express'),
mongo = require('mongodb'),
Server = mongo.Server,
MongoClient = mongo.MongoClient,
Db = mongo.Db,
http = require('http'),
app = express(),
httpServer = http.createServer(app),
bodyParser = require('body-parser'),
server = new Server('host.mongohq.com', 10066, {auto_reconnect : true}),
db = new Db('myDb', server);
db.open(function(err, client) {
client.authenticate('myUser', 'myPassword', function(err, success) {
console.log('Authenticated');
});
});
var cases = require('./routes/cases'),
menu = require('./routes/menu');
But then when I try to reference my db var in eg menu.js like this:
db.collection(myCollection, function(err, collection) {});
I get an error that db is not defined.
Obviously I can move all the mongodb declarations down to both my menu.js and cases.js file but that's just very elegant. So how do I create one mongodb instance var and refer to it from my included files?
Thanks in advance...
You need to require server.js in your menu.js file.
Your db object isn't global. If you want it to be, declare it without var.

node.js mongo db write concern

I am running node.js 10.22, windows 8 and mongodb not sure what version, but I just downloaded it today, when I run my code I am getting a message, please ensure you set the default write concern, I am trying to follow a YouTube video, and there is mention of this, and I am finding little about it on the internet, from what i found, when I set the db i should set j:true, or safe : true/false, but neither not working for me. I do get the console log that I'm connected and the host and port, but then I get the write concern message and can't type or do anything.
var mongo = require('mongodb');
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodeintro", new mongo.Server(host,port,{Fsync: true}));
db.open(function(error){
console.log("we are connected"+host + port);
})
Tried this all type of ways as well, still no luck, best i did was get back to the db write concern message, but was not able to even connect this time. What I'm really looking for is to be able to insert anything in mongo db, and i can figure out the rest.
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var host = "127.0.0.1";
var port = mongo.DEFAULT_PORT;
ArticleProvider = function(host, port) {
this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(error){
if(error){
console.log(error)
}
else{
console.log(port,host)
}
});
};
ArticleProvider(host,port)
When using mongodb-native directly, you should now use MongoClient.connect to open a database connection pool. It will set a default write concern for you.
var mongodb = require('mongodb');
mongodb.MongoClient.connect('mongodb://localhost/nodeintro', function(err, db) {
// db is your open nodeintro database connection pool here
});
MongoClient was a somewhat recent addition so the tutorial you're working from likely pre-dates it.
If you use {w:1} parameter in your insert or update operation, you might give this error. To overcome you can use {journal:true} parameter in your db settings.
For instance;
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON;
var db = new Db('Your DB Name', new Server('192.168.170.128', 27017), { journal : true });
db.open(function(err, db) {
var collection = db.collection('user');
collection.findOne({'_id':req.session.User._id}, function(err, user){
// some codes what do you want
collection.save( user, {w: 1}, function(err, user_id) {
// just close the db connection
db.close();
});
});
});

Resources