Unable to deploy nodejs-mongodb project on heroku - node.js

My connection file looks like this:
var mongo = require('mongodb');
var dbName = 'KrishiMoney';
var mongoUri = process.env.MONGOLAB_URI
/* establish the database connection */
var db ;
mongo.MongoClient.connect(mongoUri, {server:{auto_reconnect:true}}, function (err,database){
if (err) {
console.log(e);
} else{
//console.log('connected to database :: ' );
db = database;
}
});
var accounts = db.collection('accounts');
This gives the following error:
var accounts = db.collection('accounts');
^
at Object.Module._extensions..js (module.js:467:10)
TypeError: Cannot call method 'collection' of undefined
My guess is that the db variable is not getting correct value.
What is the correct way to populate the db variable when connecting using MongoClient?

The callback function you pass to the MongoClient.connect method will be executed asynchronously after the connection is established so at the point when you call db.collection('accounts') db variable is undefined.
Try wrapping the rest of your code which works with the database inside the callback function, which will make sure it is executed after the connection is established

Related

Type Error: Cannot read property 'hasListCollectionsCommand' of null

I'm trying to get all collection names in mongodb (v4.0.2) and using mongodb#3.1.10 nodejs driver. From the docs, I can see that listCollections might work, but running the following:
const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
console.error(error)
console.log(JSON.stringify(collectionNames))
})
… leads to this error:
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
at db.createCollection ({path}/sampleMongoDB.js:19:8)
at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
My questions are:
Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
If not, what's the correct way to query?
I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.
Here's a sample code that worked (Ref. to MongoDB guides)
const options = {
useNewUrlParser: true, // Add this, if you wish to avoid {https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}
const client = new MongoClient(connectionUri, options)
return client.connect().then(() => {
const db = client.db(dbName)
return db.listCollections()
.toArray()
.then((collections) => {
// Collections array
})
})
#Community mods - if required, kindly close this question.

voltdb-client-nodeJS doesn't work about #AdHoc proceduer

I followed the voltdb-client-nodeJS, and implement the #AdHoc query function, but the "read" function didn't callbacked, so that can't get any queried results, can't determine if the connection is successful, too.
[callProcedure code]
var query = resultsProc.getQuery();
query.setParameters(["select * from Q_SHIPPINGCARRIERHISTORY_STREAMING where TrackingNumber=431476575751"]);
client.call(query, function read(errorCode, eventCode, results){
...
}, function write(errorCode, eventCode, results){
...
});
[connect DB code]
var config = new VoltConfiguration();
config.host = "s7biapp26";
config.port = 8080;
var client = new VoltClient([config]);
client.connect(function(code, event, results){
...
});
On the second attempt, can't require('voltjs') or require('volt') after npm install voltjs(version:voltjs#0.2.0).
So, could you provide a more detailed documentation about the voltdb-client-nodeJS, or paste a simpler demo of #AdHoc, thank you very much!
The key is connected voltdb failed by error code in connect callback function, I tried to remove the port, then connected success!
The secondly, requiring the module should require('voltjs/lib/client').
referenced the links:
https://github.com/VoltDB/voltdb-client-nodejs/issues/12
https://forum.voltdb.com/forum/voltdb-discussions/building-voltdb-applications/577-nodejs-client-for-helloworld

How to work with NumberLong() with nodejs mongo driver

I need to insert data into my mongoDB, like such:
db.collection('Test').insert({
"Name" : "Some",
"UserID" : NumberLong(2147483647),
...
Inserts should happen from a nodejs script that interacts with mongo db
All is well, except for the NumberLong().
I'm getting the following error:
ReferenceError: NumberLong is not defined
at /root/MongoPolluter/MongoPolluter.js:107:23
at connectCallback (/root/MongoPolluter/node_modules/mongodb/lib/mongo_client.js:505:5)
at /root/MongoPolluter/node_modules/mongodb/lib/mongo_client.js:443:13
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
What I have tried:
adding var BSON = require('bson'); after installing it. Maybe I should use BSONElements?
Read this: MongoDB differences between NumberLong and simple Integer? - from which I go the notion that I could use the NumberLong only from mongo shell? Not sure if that is correct.
Also read about this: var Long = require('mongodb').Long; - should I just replace NumbreLong() w/ Long.fromString('')? Is there no way of getting the NumberLong() to work?
Thanks
NumberLong is using for mongo shell only. If you use in nodejs (javascript) it no mean.
I use mongoose and only Number type of data
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var MyNumber = mongoose.model('my_number', { long_number: Number });
var record = new MyNumber({ long_number: 1234556 });
record.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('ok');
}
});
// have to defind ObjectId when use even it a default type data of mongodb
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');

MongoDB - Error: invalid schema, expected mongodb

I'm new in building application with MEAN Stack, I'm trying to build a real time chat app, here is my server side :
console.log("Server running...!");
var mongo=require('mongodb').MongoClient;
var client=require('socket.io').listen(8080).sockets;
mongo.connect('localhost:27017/db/chat',function(err,db){
if(err) throw err;
client.on('connection',function(socket){
console.log('someone has connected !');
//waiting for input
socket.on('input',function(data){
console.log(data);
});
});
});
I am sure that i created a data base called chat with mongodb, also mongo is waiting for connection. But when i run the server with node server.js an error occurs :
Server running...!
C:\Users\azus\Desktop\Psirt\codemaster\node_modules\ mongodb\lib\url_parser.js:20
throw new Error('invalid schema, expected mongodb');
^
Error: invalid schema, expected mongodb
at module.exports (C:\Users\azus\Desktop\Psirt\code-master\node_modules\mong
odb\lib\url_parser.js:20:11)
at connect (C:\Users\azus\Desktop\Psirt\code-master\node_modules\mongodb\lib
\mongo_client.js:125:16)
at Function.MongoClient.connect (C:\Users\azus\Desktop\Psirt\code-master\nod
e_modules\mongodb\lib\mongo_client.js:109:3)
at Object.<anonymous> (C:\Users\azus\Desktop\Psirt\code-master\server.js:6:8
)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
C:\Users\azus\Desktop\Psirt\code-master>
I had been blocked at this phase for weeks, could anyone help on this?
Thanks.
This is because you are using the connection string in an improper format.
You are using localhost:27017/db/chat while it should be mongodb://localhost:27017/db/chat
The pattern for the connection string is mongodb://<HOSTNAME>:<PORT>/<DBNAME>
Article for reference: https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html#mongoclient-connect
I just had this issue as well and it was because I had the protocol wrong:
mongo://localhost:27017/test
The protocol being wrong can also cause this error. It should be like this:
mongodb://localhost:27017/test
Sometimes, error might be with the quotes around environment variables. Remove them once and try. Might help.
Error might be with :
set DATABASE_URI='mongodb://localhost:1000/my_app' && node index.js
Correct command will be:
set DATABASE_URI=mongodb://localhost:1000/my_app && node index.js
Try this, it works:
mongoose.connect('mongodb://localhost:27017/shopping');
Just figured out the same problem. Damned windows save quotes in environment.
So if you use windows and wrote this way SET MONGO_URL="mongodb://localhost:27017/{name of your db}" It is not correct.
Correct way is SET MONGO_URL=mongodb://localhost:27017/{name of your db} without quotes.
Also i discovered that you must write protocol exactly - mongodb.
There is code what check the protocol from file url_parser.js
var result = parser.parse(url, true);
if(result.protocol != 'mongodb:') {
throw new Error('invalid schema, expected mongodb');
}
the working code would be like this
don't forget to replace username, password & URL
const socketClient = require('socket.io').listen(4000).sockets;
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>#cluster0-saugt.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
socketClient.on('connection', function (socket) {
//Need to Get the Database first before trying to access the collections.
let chat = client.db("test").collection('chats');
// Get chats from mongo collection
// perform actions on the collection object
chat.find().limit(100).sort({ _id: 1 }).toArray(function (err, res) {
if (err) {
throw err;
}
// Emit the messages
socket.emit('output', res);
});
});
});
Might seem obvious, but you'll also encounter this error when you pass invalid values in general to the mongo client, e.g. undefined. Ran into this when I was referencing the wrong key on a config object.
Change content of this line from
mongo.connect('localhost:27017/db/chat',function(err,db)
to
mongo.connect('mongodb://localhost:27017/db/chat',function(err,db)
Then you can connect MongoDB database successfully.
update your mongodb npm version

Will mongoose support initializeOrderedBulkOp() which is a new feature in Mongo DB - 2.6

Am using mongoose - 3.8.8 to connect to Mongo DB. I tried out initializeOrderedBulkOp() - a new feature of MongoDB - 2.6 in mongo Shell and i got proper output. But am not able to do the same with mongoose.
Here is a sample code
var mongoose = require('mongoose');
var conn = mongoose.createConnection('mongodb://localhost:27017/testDB');
conn.on('error', function callback (err,data) {
console.log('Error in connecting to DB');
});
var Schema = mongoose.Schema,
schema = new Schema({id:Number},{strict:false}),
modelObj = conn.model('', schema, 'documents');
var query = modelObj.initializeOrderedBulkOp();
Am getting error like
"modelObj has no method 'initializeOrderedBulkOp"
Any suggestions on this ???
You're really close. You need to drop down a level to the native driver. You can do that like so:
var query = modelObj.collection.initializeOrderedBulkOp();
From there you can do things like:
// queue a doc to be inserted
query.insert({ name: 'Some Name' })
// ... more inserts ...
// execute the bulk operation
query.execute(next)
One thing to note though, the un-ordered equivalent, initializeUnOrderedBulkOp(), does not seem to exist in version 3.8.9.

Resources