Node js (Express) freezing in mongodb operation - node.js

I have a code that accepts a post request and inserts a string into mongodb database.
app.post('/post_comment', function(req, res) {
Predicts.findOne({'id': parseInt(req.body.id)}, function(err, card) {
console.log('')
console.log(card)
console.log('')
if (card) {
Users.findOne( { 'userid': req.user ? req.user.userid : undefined }, function(err, user) {
console.log(user)
console.log('')
Predicts.update({'_id': card._id},
{$push : {comments: {login: user ? user.login : 'anonymous', content: '123'}}},
function(err, card1) {throw(err);
console.log('---')
console.log(card1);
})
})
}})
res.redirect('back')
})
This code result in total freezing of node process. Only restart of the node process can help.
Debugging shows, that first four console.log operations work as supposed, but console.log('---') doesn't happen. This means that Predicts.update doesn't work, but it is really works, and I can see the result of this request in the database. What's the hitch?
Upd: I have replaced Predicts.update to Predicts.find but result is still the same. Collback doesn't work, and node process freezing.
Upd2: I established that node is not freezing, but returns only content that doesn't require to mongodb.

According to the node-mongodb docs, the update function looks like:
collection.update(criteria, objNew, options, [callback]);
So if you want to use a callback, it should be the 4th parameter, and the 3rd should be your options (e.g. multi:true) or else {}.

Related

Cannot get posts from MongoDB using gulp-data

Approach: Use gulp to create static html with posts from mongodb
Stack:: express, mongodb, pug, gulp
TL:DR
I have a express app with connected mongodb and a few posts which are displayed on my landingpage. Per server everything works, it also runs on a prod-environment. But in addition to this I also want a static version of my landingpage.
I know there are many fancy static site generators out there, but I'm a fan of gulp and want it handmade =)
I have this gulptask which already connects per MongoClient to my local DB (db: passport, collection: posts) and console.logs my posts
I think this is not the way, but I can log the posts in the data function successfully
gulp.task('db-test', function() {
return gulp.src('views/index.pug')
.pipe(data(function(file, cb) {
MongoClient.connect('mongodb://localhost:27017/passport', function(err, db) {
db.collection('posts').find().forEach(function(doc) {
console.log(doc) // This logs each of my posts from the mongodb - yayy but how to pass it correctly to the pug function below?
});
if(err) return cb(err);
cb(undefined, db.collection('posts').find());
});
}))
.pipe(pug({
// here Im using a static array, otherwise the posts are not logged in the data function
locals: {posts: [{title: "blabal"}, {title: "heyhey"}]}
}))
// If im doing like in the instruction of gulp-data, it breaks in my template
// .pipe(pug({}))
.pipe(gulp.dest('./dist'))
});
Template
ul
each val in posts
li= val.title
When i remove this dynamic part, the gulp taks generates my html without any problems.
The version how it should work (but doesn't)
gulp.task('db-test', function() {
return gulp.src('views/index.pug')
.pipe(data(function(file, cb) {
MongoClient.connect('mongodb://localhost:27017/passport', function(err, db) {
if(err) return cb(err);
cb(undefined, db.collection('posts').find());
});
}))
.pipe(pug({})) // now my gulp-pug tasks says cannot find length of undefined = no posts found or just accessing the Cursor from the mongo collection - i dont know...
.pipe(gulp.dest('./dist'))
});
When i debug my gulp task i see that db.collection('posts').find() is a pending promise. I also tried to resolv that, without success.
Gulp Heros out there - help me!

ERR_CONNECTION_RESET upon Backbone.save() to update model by Mongoose

Please, tell me what I am doing wrong:
My backbone view creates and saves document in mongodb by mongoose and uses the data in the view allright upon the backbone save() and fetch() methods. But when i use Backbone model.save({option: 'modified'}); with route.put() on the backend, jquery fires ERR_CONNECTION_RESET. I tried lots of things i found in the net, but they did not work. Maybe i need to use ajax.Prefilter or something of this kind, but i do not know exactly what to do.
the piece of code in backbone view firing update is:
this.user.save({ options: 'modified' }, {
wait: true,
success: function(model, response) {
console.log('saved');
},
error: function(model, error) {
console.log(error);
}
});
in router index.js
router.put('/user/:id', require('./user').put);
it works because on GET route it works perfectly well.
in user.js
exports.put = function(req, res) {
var query = { _id: req.params.id };
User.update(query, { options: req.body.options }, function(){
res.send('ok');
});
};
I also experimented a lot with id or _id, and various ways of using mongoose update, like
User.findOne({ _id: req.params.id }, function (err, doc){
if (err) return console.log(err);
doc.options = req.body.options;
doc.save(function(err){
res.json(doc);
});
});
and others such like. It did not work. Here is the error (it must be the key to my problem, but i cannot figer it out)
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience.
PUT http://localhost:3000/user/56349be42b19125405c2d66a
net::ERR_CONNECTION_RESET
It was silly: maximum req size exceeded. Cured by setting
app.use(bodyParser.json({limit: '16mb'}));
app.use(bodyParser.urlencoded({ limit: '16mb', extended: true }));

Node.js delete request

I have a node.js application with Express for routing and Mongoose for the database access.
I have this HTTP DELETE request that is deleting an entry in the database if certain requirements are met.
.delete(function (req, res) {
Movie.findOne({_id: req.params.id
}, function (err, movie) {
if (err)
res.send(err);
for (var i = 0, len = movie.actors.length; i < len; i++) {
if (movie.actors[i].actor == "Chuck Norris"){
res.status(403).send({ message: 'Cannot delete Chuck Norris' });
}
else {
Movie.remove({_id: req.params.id
}, function (err, movie) {
if (err)
res.send(err);
res.json({message: 'Movie deleted'});
});
}
}
});
});
If I send a HTTP DELETE with the ID of a film, it will check in the actors list if Chuck Norris is in the movie and I will prevent the deletion if he is there.
The problem is that my console is returning me this error :
Error: Can't set headers after they are sent.
So I presume that this an issue with my callbacks. Due to the asynchronus nature of node.js the "slow" database call made that my .delete sent the headers before the findOne finished ?
How can I manage to validate before deletion and send a proper http error code if the deletion is not possible ?
Be careful when you respond to a request multiple times in the same scope like that. On error you should prepend return to res.send(err) so that execution will not continue further. The same goes for your res.status() in the for-loop.

Nodejs inserting data to mongodb. It takes too much time

Hi i am developing nodejs application. I am inserting data to mongodb but my page always in 'loading' mode. But strange thing is my data inserted to mongodb immediately but page load not stopping. My code is shown below:
app.post('/Management/Post/New',function(req, res){
new Post({
title:req.body.post.title,
body:req.body.post.body,
keywords:req.body.post.keywords
}).save(function (err, docs){
if(err) {
return res.render(__dirname + "/views/createpost", {
title: 'Yeni Gönderi Oluştur',
stylesheet: 'postcreate',
error: 'Gönderi oluşturulurken bir hata ile karşılaşıldı'
});
}
console.log('Gönderi oluşturuldu');
});
});
Have no idea.
You only send a response when there is an error. If there's no error, you server never sends anything back: that's why the page seems to always be loading.
You need to send a response when you have no error, like this:
.save(function (err, docs){
if(err) { // Executed when there was an error with Mongo
return res.render(...);
} else { // Executed when everything is fine
return res.render(...);
}
});
You aren't handling the success scenario except for a console.log. You need a res.render() or res.redirect() on success, not just error

Node.js app becomes unresponsive if I reload multiple times in quick succession

I'm developing a node.js app that displays a single page with map data (which will eventually be updated using an .ajax call).
Right now, my code looks like this:
app.get('/', function(req, res) {
postgres.retrieve('SELECT * FROM settings', function(err, proj_data){
if (err){
res.send(500);
}
else{
postgres.retrieve('SELECT * FROM report ORDER BY ordering', function(err, report_data){
res.render('map', {project: proj_data[0], report: report_data});
});
}
});
and postgres.retrieve is a function that uses the node-postgres client:
retrieve: function(query, complete){
pg.connect(connection, function(err, client, done){
client.query(query, function(err, results){
if (err){
done();
return complete(err, null);
}
else {
done();
return complete(null, results.rows);
}
});
});
},
Currently, if I hit f5 10 times (over, say, 10 seconds), everything seems to respond fine, but right after, memory usage goes way up and the app becomes totally unresponsive. I'm wondering if there's something in my code that's causing this problem.
Thanks!
Oops, it seems that this is an issue in Node v0.10.0 +
https://github.com/joyent/node/issues/5108

Resources