Connecting to mongodb - node.js

Code:
var Db = require('mongodb').Db,
Server = require('mongodb').Server,
Client = new Db('test', new Server('127.0.0.1', 52235, {}))
In Function:
...
Client.open(function(err, pClient) {
Client.collection('test_insert', function(err, collection){
collection.find().toArray(function(err, results) {
console.log(results);
});
});
// etc.
});
This shows error: Cannot read property 'arbiterOnly' of undefined
can you help me?

This error occurs because it couldn't connect to the server and so the configuration information wasn't properly received. Probably you are using the wrong port: try 27017.

Related

cannot read property query of undefined

ErrorMy file database/index.js
I´m trying execute a query on my heroku database, but any request to the database causes this error.
const {Pool} = require('pg');
const pool =
new Pool({connectionString : Process.env.DATABASE_URL, ssl : true});
module.exports = {
query : function(text, values, ret_cb, err_cb){
pool.connect(function(err, client, done){
client.query(text, values).then(ret_cb).catch(err_cb);
});
}
};
Check the err value in your callback from pool.connect(...), you're probably getting a connection error.
The simplest debugging is to log out the values of err and client:
pool.connect(function(err, client, done){
console.log('err=', err);
console.log('client=', client);
client.query(text, values).then(ret_cb).catch(err_cb);
});
For interactive debugging it might be work looking at Debugging Node.js with Chrome DevTools.

Improving performance of inserting into Mongo from ActiveMQ

The basic idea of the following code is I read messages off an ActiveMQ Artemis installation and insert them into a MongoDB instance.
It works well for up to a hundred or so messages per second but crashes if I throw a few thousand at it. My first guess would be the constant opening and closing of database connections. Should I also think about using an in-memory store and doing bulk database inserts?
The code is all running in node using the mqtt and mongodb npm packages. The code below, the database and the queue are all running in docker containers if it makes any difference.
var mqtt = require('mqtt'),
client = mqtt.connect('mqtt://mq:1883', {
username: "*************",
password: "*************"
}),
MongoClient = require('mongodb').MongoClient,
ObjectId = require('mongodb').ObjectID,
assert = require('assert'),
url = 'mongodb://db:27017/uo-readings';
client.on('connect', function () {
client.subscribe('readings');
});
client.on('error', function(error){
console.log(error)
});
client.on('message', function (topic, message) {
console.log(message.toString());
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server.");
db.collection('readings').insertOne(JSON.parse(message.toString()), function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the readings collection.");
});
client.end(function(){
console.log("Closing Connection.");
db.close();
});
});
});
See #Jonathan Muller's comment above

Problems Deploying a Node.js app on Heroku Using MongoLab

I'm attempting to deploy a very simple app to Heroku. The code for the application can be found on Ray Wenderlich's site, here: http://www.raywenderlich.com/61078/write-simple-node-jsmongodb-web-service-ios-app I keep getting the same error whenever I try to have Heroku compile the code...
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
var mongoPort = 41140;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort)); //B
mongoClient.open(function(err, mongoClient) { //C
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1); //D
}
var db = mongoClient.db("heroku_app23491233"); // E
collectionDriver = new CollectionDriver(db); //F
});
When I type heroku logs, the error I get comes from if (!mongoClient) above...
app[web.1]: Error! Exiting... Must start MongoDB first
I'm sure the problem lies somewhere in my attempt to connect to the MongoLab database. I've copied the URI from MongoLab and I've created a user with the proper credentials.
I can connect to localhost just fine with very similar code, so I'm not sure what is going wrong in this example.
Thank you.
Based on the docs, my best guess is that it's because the Server constructor expects the first argument to contain only the host name (in the case of your MongoLab, ds041140.mongolab.com). However, I think you can pass your connection string into MongoClient.connect:
// Make sure to replace username and password with the proper values.
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
MongoClient.connect(mongoHost, function(err, db) {
if (err) return console.log(err);
db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
db.close();
if (err) return console.log(err);
console.log('Okay', result);
});
});
Documentation Page For MongoClient
Hopefully that helps!

connecting to mongo via open using node.js

How can I connect without to a distant database (MONGOHQ) without using MongoClient.connect() ?
var db, mongo, server;
mongo = require("mongodb");
server = new mongo.Server("mongodb://login:password#paulo.mongohq.com:10057//appname", 10057, {
auto_reconnect: true
});
db = new mongo.Db("confirmed", server, { safe: true });
the message I get from my server is
[Error: failed to connect to [mongodb://login:password#paulo.mongohq.com:10057//appname:10057]]
Any ideas ?
You want something more like this, where you define the server as a DNS name (no protocol, port, auth or path):
server = new mongo.Server("paulo.mongohq.com", 10057, {
auto_reconnect: true
});
db = new mongo.Db("confirmed", server, { safe: true });
and then once db is defined:
db.open(function(erreur, db) {
db.authenticate('user', 'name', function(err, result) {
//
});

Node.js connects to MongoDB 5 times

I've been looking for a way to do various operations on a mongo database, depending on which route a user connects to on my website. So doing a html-post to www.mysite.com/data would add info to a mongo DB, and doing a html-get at the same url would get data from the same database. I managed to solve that, but everytime I turn on my server with the website I get 5 connections registred at the mongo database. Why is this, and is it bad?
My code:
I'm runing this code in mongo.js:
var mongodb = require('mongodb');
module.exports.init = function (callback) {
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
//export the client and maybe some collections as a shortcut
module.exports.client = client;
module.exports.myCollection = new mongodb.Collection(client, 'myCollection');
callback(error);
});
};
I initialize everything running (app.js):
/express set-up/
var mongo = require('./mongo.js');
/.../
mongo.init(function (error) {
if (error)
throw error;
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode",3000,
app.settings.env);
});
});
And, for example, the post looks like (still app.js):
app.post('/App', function(req, res) {
users = users.concat(req.body);
res.redirect('/App');
//Add user to MongoDB
mongo.myCollection.insert({name: req.body.name, car: req.body.car, website: req.body.website, phone: req.body.phone}, {safe:true}, function(err, objects) {
if (err)
console.warn(err.message);
});
Pretty sure my redirect isn't working as I want it too here, but that's another issue.
Anny suggestions on why I get five connects every time I start the server?
The five connections are because that is the default poolSize (5). You can adjust it, as outlined in the server options docs - it also mentions the default.

Resources