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
Related
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.
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');
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();
});
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.
this is th code I am using inserting a document to mongodb.
var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}),
test = function (err, collection) {
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
test.assertEquals(1, count);
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
test.assertEquals(1, results.length);
test.assertTrue(results[0].a === 2);
// Let's close the db
client.close();
});
});
};
client.open(function(err, p_client) {
client.collection('test_insert', test);
});
but while running I am getting error
xports, require, module, __filename, __dirname) { var client = new Db('test',
^
ReferenceError: Db is not defined
at Object. (C:\Users\Basic node\cheerio\mongonode.js:1:81
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
can you suggest me how to solve this problem
thanks in advance
Please import all the required modules, which you are using. Db is not defined points out that Db is defined in some other module or you have forgot to declare it.
You'll notice this exact code block posted in a number of different stackoverflow questions. The problem here is that this is a copy and pasted code block from mongodb's documentation, as is in fact the first example of a mongodb nodejs program.
https://npmjs.org/package/mongodb
You'll find this under "Introduction" as "A simple example of inserting a document."
It's clearly an incomplete example, but a lot of people are just trying it out to see if they've got everything installed correctly and immediately run into a wall.
Most people will have installed the mongodb driver, but will be missing something at the top like this:
var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;
I also fell into the copy-paste trap here and ran into another issue with the "assertEquals" method not existing. I've seen other people reference that function in other places on the web, but not really sure how it works.
In any case, to make it work for me, I required the assert module:
var assert = require('assert');
And then I replaced the assertEquals lines with something like this:
assert.equal(1, count, "Unexpected result");
Note that you're going to run into an issue if you've run this a couple of times; it's going to count the number of things in that table, and there is going to be more than one.
You'll have to figure out how to get into mongo's CLI and remove them to get it to run successfully.
Try to install mongodb native driver
npm install mongodb