How to work with NumberLong() with nodejs mongo driver - node.js

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');

Related

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

mongodb connect by mongoskin error

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();
});

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

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.

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