Type Error: Cannot read property 'hasListCollectionsCommand' of null - node.js

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.

Related

How to remove TypeError: "x" is not a function?

I am trying to learn how to make a discord bot and pull data from this API called Ergast (http://ergast.com/mrd). I found this npm (https://github.com/estevE11/f1-stats) which uses NodeJS implementation to get a historical record of F1 data from Ergast API. Sorry for the bad wording I am still trying to learn the lingo.
I followed what was stated in the npm documentation for installing it and tried using the example to get data from the API. However when I run the code in index.js I get the error "TypeError: "x" is not a function". When I go into the node_modules "f1-stats" folder and run the code from main.js I do get the correct result.
index.js:
const client = new Discord.Client(); //This will be our client
const { prefix, token } = require('./config.json');//const PREFIX = '!';
const f1s = require('f1-stats');
//module.exports.f1s = f1s; //Still causes the TypeError
f1s("2008 drivers", (res) => {
console.log(res);
});
The error message I get in index.js:
f1s("2008 drivers", (res) => {
^
TypeError: f1s is not a function
at Object.<anonymous> (C:\Users\RyanPC\Documents\DiscordBot\index.js:8:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
node_modules/f1-stats/main.js:
const f1s = require("./f1-stats"); // "./" is used because module is located in the same folder as the Node.js file
f1s("2008 drivers", (res) => {
console.log(res);
});
when I run it in node_modules/f1-stats/main.js:
{ MRData:
{ xmlns: 'http://ergast.com/mrd/1.4',
series: 'f1',
url: 'http://ergast.com/api/f1/2008/drivers.json',
limit: '30',
offset: '0',
total: '22',
DriverTable: { season: '2008', Drivers: [Array] } } }
Because f1-stats doesn't export anything so when you import it. It is empty. The correct file you need to import is f1-stats/f1-stats.
const f1s = require('f1-stats/f1-stats');
try importing f1s properly , you are getting error because you have not imported the function properly , in other words...check what is being exported from what are you trying to import....hope it solves the problem.

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

Unable to deploy nodejs-mongodb project on heroku

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

Can't save Bookshelf model instance

I'm experimenting with Bookshelf, and made a small program to learn how it works.
Unfortunately it seems it doesn't really work, as Knex complains that it haven't been initialized.
I'm using Bookshelf version 0.3.1, and Knex version 0.2.6.
When I run my simple test program, I get the following error:
/home/joachimp/tmp/ks/db/node_modules/knex/knex.js:20
throw new Error('The Knex instance has not been initialized yet.');
^
Error: The Knex instance has not been initialized yet.
at Knex (/home/joachimp/tmp/ks/db/node_modules/knex/knex.js:20:13)
at _.extend.builder (/home/joachimp/tmp/ks/db/node_modules/bookshelf/bookshelf.js:384:14)
at query (/home/joachimp/tmp/ks/db/node_modules/bookshelf/bookshelf.js:1294:35)
at _.extend.query (/home/joachimp/tmp/ks/db/node_modules/bookshelf/bookshelf.js:379:14)
at new Bookshelf.Sync (/home/joachimp/tmp/ks/db/node_modules/bookshelf/bookshelf.js:823:26)
at _.extend.sync (/home/joachimp/tmp/ks/db/node_modules/bookshelf/bookshelf.js:389:14)
at _.extend.save (/home/joachimp/tmp/ks/db/node_modules/bookshelf/bookshelf.js:263:24)
at Object. (/home/joachimp/tmp/ks/db/dbtest.js:20:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
And the program is simply this:
var Bookshelf = require('bookshelf');
Bookshelf.Initialize('sqlite3', {
client: 'sqlite3',
connection: {
filename : './dbtest.sqlite3'
}
});
var TestModel = Bookshelf.Model.extend({
tableName: 'TestModel',
initialize: function() {
},
name: 'foo'
});
var test = new TestModel;
test.save(); // <- Line 20
console.log('All done');
The documentation is scarce, and examples even more so, or I might have figured it out already.
I have also tried creating collections and putting model instances in them, and using sync object with the insert method. All with the same result of Knex not being initialized.
What am I missing? Do I have to initialize Knex separately? And (yes I know it's off-topic) are there any simple examples or tutorials to learn from?
So this was sort of a bad design decision, there is a try/catch block in "Knex" wrapping the client initialize code, so there's an unrelated error with the client other than using the wrong name, it gets silenced.
I'm guessing there's something wrong with the sqlite3 client you're using, this has been fixed in the latest version. Try it with the latest Bookshelf 0.5.1 and Knex 0.4.3 with this code:
var Bookshelf = require('bookshelf');
var bookshelf = Bookshelf.initialize({
client: 'sqlite3',
connection: {
filename : './dbtest.sqlite3'
}
});
var TestModel = bookshelf.Model.extend({
tableName: 'TestModel',
initialize: function() {
},
name: 'foo'
});
var test = new TestModel;
test.save(); // <- Line 20
console.log('All done');
As for examples, I'm hoping to get one together soon... otherwise, looking at the code in the integration tests would be your best bet.

Resources