I'm starting webapps development with Node, so I'm quite new with this technology.
I've done several examples and managed to make it run.
However, now I'm trying to use Mongodb but I'm not able to make it run properly. It seems that the connection is working but when I call the find() method and I go to localhost:3000/near (which is the url that makes the findAll docs), the browser spends about a half a minute loading and finishes returning nothing (ERR_EMPTY_RESPONSE).
This is my code:
app.js
app.get('/near', function(req, res){
server.findAll( function(error,docs){
res.render('near', {
title: 'Cerca tuyo!',
places:docs
});
})
});
And this my Server.js
//constructor
AppServer = function(host, port) {
this.db= new Db('node-mongo-places', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
//Devuelve la colección de "places"
AppServer.prototype.getCollection= function(callback) {
this.db.collection('places', function(error, places_collection) {
if( error ) callback(error);
else callback(null, places_collection);
});
};
//Devuelve todos los contenidos de la DB places
AppServer.prototype.findAll = function(callback) {
this.getCollection(function(error, places_collection) {
if( error ) callback(error)
else {
places_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
I have debugged the code writing console.log() and it seems that it does not reach to the callback function from places_collection.find().toArray(function(error, results) {
Any idea why the server does not return anything?
!!! EDIT:
I found some piece of code to test if the connection to mongodb is alright and it says that it's not: [Error: failed to connect to [localhost:27017]]
So the problem is in the connection. Should I run mongodb first? I thought that the app.js itself would did that for me!
Got the answer for this question:
As said, I thought that npm install mongodb would install the whole thing. However, it does not, so I managed to fix it by executing sudo apt-get install mongodb.
Once installed, the app itself runs mongodb.
I added this to my mongodb open() method so as I could see what was happening:
this.db.open(function(error,db){
if(error) {
console.log(error);
} else {
console.log("connected to mongod with no problems...");
}
});
Related
I'm new to Electron and trying to make 1 st application in which I need to connect it to a SQL server database for data storing/retrieving. I've have installed this plugin (https://www.npmjs.com/package/mssql#connect-callback) and followed their instructions but got no success regarding the connection. The weird part is that I also get no error or whatever showing in the console so I'm totally lost. Any help would be much appreciated, thank you guys.
Ps: I'm sure that there's no problem with the database since I can still connect to it using the same config setting below with a database client manager tool.
Below is the code I've used for simple testing connection.
<script type="text/javascript">
$(document).ready(function () {
const electron = require('electron');
const sql = require('mssql');
const config = {
user: 'ql*****',
password: 'qlh****',
server: '123.20.****',
database: 'QLHS'
};
async () => {
try {
await sql.connect(config);
const result = await sql.query`select * from DM_DONVI`;
console.dir(result);
} catch (err) {
console.log(err);
}
};
});
</script>
The link you provided is working. I tried the same. The error log can be seen in view->Toogle Developer Tools. The issue is you need install mysql.
npm install mysql --save
Then the code works fine.
Thank you Mr :D Actually, the thing that didn't work in my original post is the async part. Changing that to this and everything is fine now:
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from DM_DONVI', function (err, recordset) {
if (err) {
console.log("Something went wrong")
}
else {
var result = JSON.stringify(recordset);
console.log(recordset.recordsets[0]);
}
});
});
I'm attempting to deploy a very simple app to Heroku. The code for the application can be found on Ray Wenderlich's site, here: http://www.raywenderlich.com/61078/write-simple-node-jsmongodb-web-service-ios-app I keep getting the same error whenever I try to have Heroku compile the code...
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
var mongoPort = 41140;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort)); //B
mongoClient.open(function(err, mongoClient) { //C
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1); //D
}
var db = mongoClient.db("heroku_app23491233"); // E
collectionDriver = new CollectionDriver(db); //F
});
When I type heroku logs, the error I get comes from if (!mongoClient) above...
app[web.1]: Error! Exiting... Must start MongoDB first
I'm sure the problem lies somewhere in my attempt to connect to the MongoLab database. I've copied the URI from MongoLab and I've created a user with the proper credentials.
I can connect to localhost just fine with very similar code, so I'm not sure what is going wrong in this example.
Thank you.
Based on the docs, my best guess is that it's because the Server constructor expects the first argument to contain only the host name (in the case of your MongoLab, ds041140.mongolab.com). However, I think you can pass your connection string into MongoClient.connect:
// Make sure to replace username and password with the proper values.
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
MongoClient.connect(mongoHost, function(err, db) {
if (err) return console.log(err);
db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
db.close();
if (err) return console.log(err);
console.log('Okay', result);
});
});
Documentation Page For MongoClient
Hopefully that helps!
I'm using node js, express and postgresql as backend.
This is the approach I used to make a rest API:
exports.schema = function (inputs, res) {
var query = knex('schema')
.orderBy('sch_title', 'asc')
.select();
query.exec(function (err, schemas) {
if(err){
var response = {
message: 'Something went wrong when trying to fetch schemas',
thrownErr: err
};
console.error(response);
res.send(500, response);
}
if(schemas.length === 0){
var message = 'No schemas was found';
console.error(message);
res.send(400, message);
return;
}
res.send(200, schemas);
});
};
It works but after a while postgres logs an error and it's no longer working:
sorry, too man clients already
Do I need a close each request somehow? Could not find any about this in the express docs. What can be wrong?
This error only occurs on production server. Not on developing machine.
Update
The app only brakes in one 'module'. The rest of the app works fine. So it's only some queries that gives the error.
Just keep one connection open for your whole app. The docs shows an example how to do this.
This code goes in your app.js...
var Knex = require('knex');
Knex.knex = Knex.initialize({
client: 'pg',
connection: {
// your connection config
}
});
And when you want to query in your controllers/middlewares...
var knex = require('knex').knex;
exports.schema = function (req, res) {
var query = knex('schema')
.orderBy('sch_title', 'asc')
.select();
// more code...
};
If you place Knex.initialize inside an app.use or app.VERB, it gets called repeatedly for each request thus you'll end up connecting to PG multiple times.
For most cases, you don't need to do an open+query+close for every HTTP request.
I have a one-shot Node script that makes some changes to a MongoDB database on MongoLab. However, once it finishes, it never exits the event loop (I always have to ctrl+C it), no matter how much db.close() and db.logout() calling I do.
What's strange is, if I start a local running instance of mongod and connect to that, the script finishes fine, but the remote connection just never ends.
Here is a short version of my script that still has the issue (taking the URL to the server on the command line). What's going on?
var mongodb = require("mongodb");
function onSuccess(cb){
return function(err) {
if (err) {
console.error(err)
} else {
cb.apply(this,Array.prototype.slice.call(arguments,1))
}
}
}
console.log("Connecting to "+process.argv[2]+' ...');
mongodb.MongoClient.connect(process.argv[2],onSuccess(function(db){
console.log("Connected.");
db.logout(onSuccess(function(logoutResult){
db.close(onSuccess(function(closeResult){
console.log("All finished. Can has prompt return nao?")
}));
}));
}));
Just tried the code with driver version 1.2.7/1.2.8 and the newest 1.2.9 against mongolab and it works correctly. So more likely its a weird combination of driver/os/node version that's causing this. I suggest upgrade your node and driver to the latest version and try again.
I suspect it has to do with the way you have defined your closures but I cannot quite put my finger on it.
For what is worth, below is the approach that I use and this does close the connection as expected:
MongoClient.connect(dbUrl, function(err, db) {
if(err) return callback(err);
var collection = db.collection(dbCollection);
collection.find().toArray(function(err, items){
db.close()
if(err) return callback(err);
callback(null, items);
});
});
You can find a full example here: https://github.com/hectorcorrea/mongoDbSample
I am learning and trying simple example using node.js and mongoskin. here is my function below
Problem following function is, if the mongodb server is disconnected then also I get the "err=null" hence not able catch connection error. If I restart node.js server (while mongoDB server is still disconnected) I get error as
"[Error: failed to connect to [server-aa070:27017]]"
// Process messages from client
app.post('/send', function(req, res){
var message = {
id: i++,
nickname: req.param('nickname', 'Anonymous'),
text: req.param('text', ''),
created_at: new Date()
};
conn.chat_log.insert(message, function(err) {
if(err!==null){
console.log(err);
}
else {
console.log(message);
console.log(err);
}
});
res.json({status: 'ok'});
});
I'm new to node.js and mongodb, but why are you using if(err!==null) rather than if(err)? If I'm understanding correctly, wouldn't this solve your problem?
Don't know about mongoskin, but for the node-mongo-native driver (the driver that mongoskin is built on), the author said:
Note that there's no reason to pass a callback to the insert or update
commands unless you use the safe:true option. If you don't specify
safe:true, then your callback will be called immediately.