A
A
Alexey Vladimirov2014-06-27 15:51:22
MongoDB
Alexey Vladimirov, 2014-06-27 15:51:22

How to export model in mongoose?

Hello gentlemen.
I started to actively study mongodb + mongoose + nodejs, I ran into a problem that I can’t solve for half a day, googling doesn’t help either.
there is a modelGroups.js file :

module.exports = function(mongoose)
{
    var db = mongoose.connection;
 
    var groupSchema = new mongoose.Schema({
        name:  {type: String, default: 'test' },
        name2: {type: String, default: 'none'}
    });
    
    // Специально, чтобы проверить, обьясню позже
    groupSchema.pre('save', function(next){
        console.log('saving ');
        return next();
    })
    // Специально, чтобы проверить, обьясню позже
    groupSchema.post('saved', function(next){console.log('saved');})
  
    var model = db.model('groupModel', groupSchema);
    return model;
}

and accordingly server.js :
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://localhost/notes');
db.on('error', console.error.bind(console, "connection error:"));
db.once('open', function callback () { console.log('Connected to database') });
// .............................................
app.get('/test', function(req, res){

    var model = require('./model/modelGroups.js')(mongoose);
    
    var m1 = new model({name:'test g 1'});
    m1.save(function(){
        res.send('saved');    
    });
});

And so an essence of a problem: does not save, stupidly.
The callback in m1.save is never called, just like post('save', ... ) is also not called/
The pre('save', ...) callback is called.
That is, it does not seem to reach the preservation.
Moreover, if all this is combined into one file, everything works. Please tell me what could be the problem.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Vladimirov, 2014-06-27
@xvladimirov

Googled.
For anyone interested, here:
stackoverflow.com/questions/10156623/mongoose-js-i...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question