I have this issue with node.js and mongodb.
I followed the example from mongodb.github.io, '
the code is:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection url
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to server
MongoClient.connect(url, function(err, db){
assert.equal(null, err);
console.log('Connected to server');
// Insert a single document
db.collection('test').insertOne({a:1}, function(err, r){
assert.equal(null, err);
assert.equal(1, r.insertedCount);
});
});
in my console i get the following error:
Object #Collection has no method 'insertOne'.
Any ideas why?
Related
I have 2 URLs, one points to a different connection string and the other to local MongoDB instance. While I establish the connection to MongoDB using MongoClient with url1 and fetch the required data from a DB/collection and lastly store it in an array.
Now I want to insert this array to a localhost MongoDB collection and on doing so I get MongoError: Topology is closed, please connect error.
app.js
var url1="someurl but not localhost";
var url2="mongodb://localhost:27017/";
router.get('/route1', function(req, res)
{
MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("customer");
dbo.collection("customer_report").find({}).toArray(function(err, result) {
if (err!=null){
console.log("Connection Failed!!"+err)
}
var customerArray =[];
for(i=0;i<result.length;i++){
backupArray.push({
a: result[i].a,
b: result[i].b,
c: result[i].c,
d: result[i].d,
});
}
console.log(customerArray);
res.json({content:customerArray});
db.close();
MongoClient.connect(url2,{ useUnifiedTopology: true }, function(err, db1) {
//Trying to establish another mongodb connection wuth new url
if (err) throw err;
var dbo = db.db("localdb");
dbo.collection("localcollection").insertMany(customerArray, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db1.close();
});
});
});
});
});
And if I don't close db.close(); then the array data gets appended to first MongoDB collection and not the local MongoDB. Looking for a solution to handle two MongoClient at the same time or a way to insert the customerArray to local MongoDB collection.
Is there a workaround where I can add the array elements to my local MongoDB collection?
In your second mongo connect block I think you want
var dbo = db.db("localdb");
to be
var dbo = db1.db("localdb");
Have you made sure those credentials work in console commands? And have you made sure the last connection through the console is closed before trying to use them in the script?
I'm trying to display mongodb data in my html page. I've already managed to insert data in db but for some reason my "get" function does not work.
I'm using node.js with express framework and Angular for front-end and routing.
This is my "get" function to retreive data from MongoDB:
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
res.render('index', {items: resultArray});
});
});
});
And my "post" which works
router.post('/insert', function(req, res, next) {
var item = {
name: req.body.name,
adress: req.body.adress,
postal: req.body.postal,
city: req.body.city,
email: req.body.email,
phone: req.body.phone,
quotation: req.body.quotation,
message: req.body.message
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('/contact');
});
i am not sure if this is the correct way to open and close mongo connection each time you are trying to query .
if you want to go for another approach then use mongoose
and follow something like this
https://pastebin.com/g7aatzzj
I think that you have a mistake in your .find().forEach function callbacks. The error handling seems to be in the endCallback not the iteratorCallback.
According to the official doc, the correct way should be :
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find({});
cursor.forEach(function(doc){
assert.notEqual(null, doc);
resultArray.push(doc);
}, function(err, doc){
assert.equal(null, err);
db.close();
res.render('index', {items: resultArray});
});
});
});
This can also be found in their unit tests
var cursor = collection.find({})
.map(function(x) { return {a:1}; })
.batchSize(5)
.limit(10);
cursor.forEach(function(doc) {
test.equal(1, doc.a);
}, function(err, doc) {
test.equal(null, err);
db.close();
test.done();
});
I think that you must have a error that is not passed to the first callback and not handled in the second one. So you do not see the error.
Try to insert an empty object to the find() function as following:
var cursor = db.collection('user-data').find({});
I have just run your code and modified it a bit for my purposes.
Please find the following snippet
//Instantiate MongoClient
var mongo = require('mongodb').MongoClient;
//Assert library (Perhaps overkill if you are writing production-level code)
var assert = require('assert');
//Express engine
var express = require('express');
//URL for my mongo instance
//Connecting to the blog database
var url = 'mongodb://localhost:27017/blog';
//Instantiate express
var router = express();
//Get operation
router.get('/get', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('posts').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
//I have no index file to render, so I print the result to console
//Also send back the JSON string bare through the channel
console.log(resultArray);
res.send(resultArray);
});
});
});
//Start listeninig
//Hardcoded port 1000
var server = router.listen(1000, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
Therefore to get this working for you:
Change the url to 'mongodb://localhost:27017/loodgieters';
Change router to '/get-data'
I hope this helps!
Also consider using splitting the implementation of the get operation to another module to help for the Separation of Responsibilities to make your code more robust.
I am trying to make a REST api in node using express. When i open the url in browser the first time, it runs fine and gives me the correct output. But when I hit the api url the second time, the app crashes with the error :
events.js:141
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
This is the code I'm using :
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'USER_NAME',
password: 'PASSWORD'
});
app.use(express.static(__dirname + '/public'));
var port = 3333;
app.get('/api/users/:user_id', function(req, res){
var lead_id = req.params.user_id;
connection.connect();
connection.query('use DB_NAME;', function (err) {
if(err) throw err;
connection.query('select * from users where user_id = ' + user_id, function (err, rows) {
if(err) throw err;
res.json(rows);
connection.end();
});
});
});
app.listen(port);
console.log("The app is running on port " + port);
Can someone tell me what am I doing wrong ?
Just remove connection.connect() and connection.end(). Then it should work.
connection.connect() should be called once or none. Because connection.query will connect I'd it not connected.
PS - connection.connect() need to be called when the connection is lost.
Try this to remove the redudant connection. This was the first result of a google search of the error message - always try to google error messages before asking SO.
Hi I tried to connect to mongodb and print all collection from a dabase in mongodb using node.js program but i am getting error. Code I tried is as below.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://ipaddressofmywebsite:27017/databasename", function(err, db) {
if(!err) {
console.log("We are connected");
var m = new MongoClient();
var db = m.selectDB("databasename");
var list= db.getCollectionNames();
console.log(list);
}
});
**I get the following error**
throw err
^
TypeError: m.selectDB is not a function
When I tried the below code as suggested in this page also i get error.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://websiteipaddress/databasename",
function(err, db) { // The db is passed in here.
if(!err) {
console.log("We are connected");
var list= db.getCollectionNames();
console.log(list);
}
});
**Error i get is**
throw err
^
TypeError: db.getCollectionNames is not a function
Kindly help me to fix this error
You don't need to select a database. You already did that in the connection string: mongodb://ipaddressofmywebsite:27017/databasename. This should work:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://ipaddressofmywebsite:27017/databasename",
function(err, db) { // The db is passed in here.
if(!err) {
console.log("We are connected");
db.collectionNames(function(err, names) {
console.log(names);
});
}
});
Here is the docs for MongoClient - About getting the collection names
Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});