mongodb connect by mongoskin error - node.js

I have tried below mentioned code to connect mongo db using mongoskin node module
var mongo = require('mongoskin');
var db = mongo.db("localhost:27017/mydb");
db.bind('mycollection');
db.mycollection.find().toArray(function(err, items) {
console.log(items)
db.close();
});
I am getting below mentioned error.
/usr/local/lib/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/url_parser.js:15
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam
^
Error: URL must be in the format mongodb://user:pass#host:port/dbname
at Error (<anonymous>)
at exports.parse (/usr/local/lib/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/url_parser.js:15:11)
at Function.MongoClient.connect (/usr/local/lib/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/mongo_client.js:164:16)
at SkinClass.SkinDb._open (/usr/local/lib/node_modules/mongoskin/lib/db.js:36:25)
at SkinClass.open (/usr/local/lib/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.SkinCollection._open (/usr/local/lib/node_modules/mongoskin/lib/collection.js:49:17)
at SkinClass.open (/usr/local/lib/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.SkinCursor._open (/usr/local/lib/node_modules/mongoskin/lib/cursor.js:28:25)
at SkinClass.open (/usr/local/lib/node_modules/mongoskin/lib/utils.js:162:14)
at SkinClass.(anonymous function) [as toArray] (/usr/local/lib/node_modules/mongoskin/lib/utils.js:116:14)
In that error it has mentioned enter username and password.I dont have username and pasword.What i have to enter for that please help me.
My mongodb version is v1.8.2,
node version is v0.10.28,
mongoskin version is v1.4.4.

The error says:
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam")
Have you tried adding the protocol? (i.e.:)
var db = mongo.db("mongodb://localhost:27017/mydb");

The answer lies in the error itself :
throw Error("URL must be in the format mongodb://user:pass#host:port/dbnam
^
Error: URL must be in the format mongodb://user:pass#host:port/dbname
In case you didn't understand , kindly do as mentioned below :
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/mydb");
db.bind('mycollection');
db.mycollection.find().toArray(function(err, items)
{
console.log(items)
db.close();
});

Related

GridFSBucketReadStream error: cannot read property 'write' of null

I'm using mongodb module to download a file from gridfs.
Here's the code -
import { Db, Server, GridFSBucket } from 'mongodb';
let gfs = new GridFSBucket(new Db(<db_name>, new Server("127.0.0.1", 27017)), {"bucketName": "fs"});
let readStreamData = gfs.openDownloadStream(<ObjectId>);
The output is the following error -
error occurred in downloadreport TypeError: Cannot read property 'write' of null
at Object.query (C:\project\node_modules\mongodb\lib\core\wireprotocol\query.js:29:19)
at Server.query (C:\project\node_modules\mongodb\lib\core\topologies\server.js:639:16)
at FindOperation.execute (C:\project\node_modules\mongodb\lib\operations\find.js:24:12)
at C:\project\node_modules\mongodb\lib\operations\execute_operation.js:168:15
at Server.selectServer (C:\project\node_modules\mongodb\lib\core\topologies\server.js:827:3)
at Server.selectServer (C:\project\node_modules\mongodb\lib\topologies\topology_base.js:363:32)
at executeWithServerSelection (C:\project\node_modules\mongodb\lib\operations\execute_operation.js:150:12)
at executeOperation (C:\project\node_modules\mongodb\lib\operations\execute_operation.js:81:16)
at Cursor._initializeCursor (C:\project\node_modules\mongodb\lib\core\cursor.js:545:7)
at Cursor._initializeCursor (C:\project\node_modules\mongodb\lib\cursor.js:191:11)
at nextFunction (C:\project\node_modules\mongodb\lib\core\cursor.js:748:10)
at Cursor._next (C:\project\node_modules\mongodb\lib\core\cursor.js:202:5)
at nextObject (C:\project\node_modules\mongodb\lib\operations\common_functions.js:234:10)
at NextOperation.execute (C:\project\node_modules\mongodb\lib\operations\next.js:26:5)
at executeOperation (C:\project\node_modules\mongodb\lib\operations\execute_operation.js:83:26)
at Cursor.next (C:\project\node_modules\mongodb\lib\cursor.js:217:12)
C:\project\node_modules\mongodb\lib\utils.js:133
throw err;
does anyone know what is it that I'm doing wrong?
PS: I also want to download and save the data I receive in a pdf file (the data is pdf content already). How can I achieve this?

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.

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

Resources