Bee San
Bee San

Reputation: 2665

Why does this simple Mongoose.js program freeze while doing a 'nested' save?

[edit]: I updated the previous question with this, using a very specific reproducible example.

This is my entire program.

I create two Schemas ASchema and BSchema with collections A and B respectively, make two objects a and b, and attempt to save them sequentially - that is, first a then b.

mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

ASchema = new Schema({
    text: String
});

BSchema = new Schema({
    val: Number
});

A = mongoose.model('A', ASchema);
B = mongoose.model('B', BSchema);

a = new A({text: 'this is a'});
b = new B({val: 5});

a.save(function(err) {
    if(err) console.log(err.message);
    else {
        console.log('saved a : ', a);
        b.save(function(err) {
            if(err) console.log(err.message);
            else {
                console.log('saved b : ', b);
            }
        });
    }
});

mongoose.disconnect();

What I expect should happen:
It should print saved a : followed by the document a, and then saved b :, followed by the document b.

What actually happens:
It prints saved a : { text: 'this is a', _id: 4ee4cab00d2c35fc04000001 } and nothing more. The program does not stop either; it stays 'stuck'.
Looking through the mongo shell, I find that a collection as (a pluralized by mongoose, that is okay) has been created, and I can see saved document in it with db.as.find(). However, I cannnot find a collection bs.

Tweak:
In the saving code, swapping the places of a and b (order of saving) causes b to be saved, and a to not be saved. So the problem is not specifically with a or b.

Question: Why does it not save the next document?

Upvotes: 2

Views: 2320

Answers (2)

Amol M Kulkarni
Amol M Kulkarni

Reputation: 21629

mongoose.disconnect();  //Do not do this as async methods keep running in background.

Don't open + close a connection for every query.

Open the connection once, and re-use it.

I do prefer following way:

MongoDBconObj.open(function(err, db) {
    //re-use db 
    // All your application codes goes here...
    //..
    http.createServer(onRequest).listen(8080);
    console.log("HTTP is listening on 127.0.0.1:8080 ");
  }); 

See the link for best practice

https://groups.google.com/forum/#!topic/node-mongodb-native/5cPt84TUsVg

Upvotes: 0

alessioalex
alessioalex

Reputation: 63653

The answer is very simple, look at your last line:

mongoose.disconnect();

You shouldn't be doing that, since there are still queries that need to be processed and you don't know when (in our case it's the second query). So what happens is the first query gets executed, Mongoose disconnects and it hangs the second query.

Solution

Delete the last line on put mongoose.disconnect(); after the last query gets executed.

Upvotes: 5

Related Questions