mongodb with nodejs - node.js

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

Related

Download plotly open source on node js

Can you download the entire module of plotly using node js. Right now, I am streaming data with plotly using node js by using my API keys. If there is a way, can yo give step by step instructions? I tried https://www.npmjs.com/package/plotly.js, but it does not work.
var plotly = require('plotly.js');
var initdata = [{x:[], y:[], stream:{token:'t2166m92ft', maxpoints:50}}];
var initlayout = {fileopt : 'overwrite', filename : 'nodenodenode5'};
plotly.plot(initdata, initlayout, function (err, msg) {
if (err) return console.log(err);
console.log(msg);
var stream1 = plotly.stream('t2166m92ft', function (err, res) {
if (err) return console.log(err);
console.log(res);
clearInterval(loop); // once stream is closed, stop writing
});
var i = 0;
var loop = setInterval(function () {
client.once('message', function (message) {
var data = { x : i , y : message.toString()};
var streamObject = JSON.stringify(data);
stream1.write(streamObject+'\n');
i++;
});
}, 5000);
});
}
when i tried install using npm install plotly.js, and ran my program I got :
\Users\intern\Documents\universal-ground-system\Node js\node_modules\plotly.js
rc\lib\index.js:397
var style = document.createElement('style');
^
ReferenceError: document is not defined
at Object.lib.addStyleRule (C:\Users\intern\Documents\universal-ground-syste
Node js\node_modules\plotly.js\src\lib\index.js:397:21)
at Object.<anonymous> (C:\Users\intern\Documents\universal-ground-system\Nod
js\node_modules\plotly.js\build\plotcss.js:61:16)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Users\intern\Documents\universal-ground-system\Nod
js\node_modules\plotly.js\src\plotly.js:30:1)
at Module._compile (module.js:409:26)
Plotly open source library can not be used in node js. But can be used on client side javascript.
I got past this to some degree, but ran into another error, so close now it seems.
When I make a dom with jsdom it doesn't like to see window for some sort of async issue probably.
If you go into REPL load the file or otherwise get to make the new jsdom object, then you can do this sort of thing in REPL that references window and the needed document.
let jsdom = lib.require('jsdom');
//let window = (new jsdom.JSDOM('<p>Hello</p>')).window;
let dom = new jsdom.JSDOM('<p>Hello</p>');
/* While just testing I do this in REPL after .load index.js
let window = dom.window;
let document = window.document;
*/
So then I get a new error after npm install canvas that needs
apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
first to properly build it on Ubuntu 16
so the new error is...
> let window = dom.window;
undefined
> let document = window.document;
undefined
>
>
> let plt = lib.require('plotly.js');
ReferenceError: self is not defined
at Object.254 (./node_modules/mapbox-gl/dist/mapbox-gl.js:509:29)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.252../window (./node_modules/mapbox-gl/dist/mapbox-gl.js:505:25)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.73.../package.json (./node_modules/mapbox-gl/dist/mapbox-gl.js:146:75)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at e (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:855)
>
I tried setting 'self' to 'document' and 'this' and get another error.
> self = document;
Document { location: [Getter/Setter] }
> plt = lib.plt = lib.require('plotly.js');
TypeError: Cannot read property 'hardwareConcurrency' of undefined
at Object.252../window (./node_modules/mapbox-gl/dist/mapbox-gl.js:505:834)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.73.../package.json (./node_modules/mapbox-gl/dist/mapbox-gl.js:146:75)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at e (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:855)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:873
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:150
Next I attempted to get window.navigator into self but that's apparently got nothing to do with the error. Somewhere else in mapbox-gl.js is glitching out.
I've only found a reference to harwareConcurrency in mapboxgl.js here
https://github.com/mapbox/mapbox-gl-js/issues/899
Seems misleading to say it's a nodejs library when it only works in the browser? https://plot.ly/nodejs/
Just now I'm seeing something about an API Key? I guess I'm barking down the wrong tree sideways. Big mistake here.

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

Node's Commander can't prompt terminal

I'm using the popular Commander npm module in a command-line program i'm building. It works great except that all of the functions it provides that solicit user input -- aka, choose, prompt, and password -- fail to work.
As an example I'm using:
program
.command('test')
.action(function(param) {
program.prompt('Username: ', function(name){
console.log('hi %s', name);
});
program.prompt('Description:', function(desc){
console.log('description was "%s"', desc.trim());
});
}
);
This results in the following error (yet it is copy and pasted directly out of the documentation/examples):
TypeError: Object # has no method 'prompt'
at Command. (lib/tg.js:780:11)
at Command.listener (node_modules/commander/index.js:249:8)
at Command.emit (events.js:98:17)
at Command.parseArgs (/node_modules/commander/index.js:480:12)
at Command.parse (/node_modules/commander/index.js:372:21)
at Object. (/lib/tg.js:806:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Try using the Node Prompt module. Install it from npm with this command:
npm install prompt --save
The docs can be found here: https://github.com/flatiron/prompt
Make sure you also require it in your code, usually at the top.
var prompt = require('prompt');
Remember, Node is non-blocking. Multiple prompts will attempt to get user input at the same time. To get around this, split your prompts up into functions and call the next prompt in the callback.
Example:
var first_prompt = function() {
var schema = {
// Read the docs on creating a prompt schema
};
prompt.start();
prompt.get(schema, function(err, result) {
// Do stuff with the input
// Call the next prompt
next_prompt();
});
};

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.

Creating temporary view in couchdb using node-couchdb-api

I am trying to connect couchdb using node-couchdb-api at nodejs level as mentioned in the following link http://dominicbarnes.us/node-couchdb-api/.My couchdb version is 1.1.1 and nodejs version is 0.6.10.
For creating temporary view as mentioned in api http://dominicbarnes.us/node-couchdb-api/api/database/tempView.html I have written the following code.
var couchdb = require("couchdb-api");
var server = couchdb.srv(localhost, 5984, false, false);
var db = server.db("test");
var map = function (doc) {
emit(null, 1);
};
var reduce = "_sum";
var query = { include_docs: true };
db.tempView(map, reduce, query, function (err, response) {
console.log(response);
});
But i am facing the following problem.
C:\Program Files\nodejs\node_modules\couchdb-api>node server.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property '0' of null
at C:\Program Files\nodejs\node_modules\couchdb-api\lib\util.js:24:39
at Array.map (native)
at Object.formatFunction (C:\Program Files\nodejs\node_modules\couchdb-api\lib\util.js:22:25)
at Object.tempView (C:\Program Files\nodejs\node_modules\couchdb-api\lib\database.js:285:28)
at Object.<anonymous> (C:\Program Files\nodejs\node_modules\couchdb-api\server.js:27:4)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
please suggest me to resolve the issue.
Thanks in advance.
sorry about the problem you were experiencing. I'm the creator of that module, and I've just pushed version 1.1.2 up to NPM which addresses your problem. (and includes a unit test to make sure it doesn't happen again)
Just update to the latest version via npm update couchdb-api and you should be set to go. Let me know if you have further issues.

Resources