Ron
Ron

Reputation: 6735

mongoose es6 doesn't work for me

I am trying to use mongoose with es6, but without any luck with the following code:

var mongoose = require('mongoose');
var co = require('co');

mongoose.connect('mongodb://localhost/test', {
    server: {
    socketOptions: {
        keepAlive: 1
    }
    }
});
mongoose.connection.on('error', function(err) {
    console.error('MongoDB error: %s', err)
});
co(function*() {
    console.log('starting');
    var schema = new Schema({
    description: {
        type: String,
        required: true
    }
    });
    console.log('creating schema');
    var s = db.model('schema', schema);
    console.log('creating doc');

    var br = new s({
    description: 'abc'
    });

    yield br.save();
});

The output is only 'starting', and hang there for ever.

Anyone could fix the issue for me?

Upvotes: 1

Views: 994

Answers (2)

Jesus M Martinez
Jesus M Martinez

Reputation: 61

Just in case someone has the same problem. Using co you always should catch the errors, if not you won't know what is wrong with it. Example of your code working.

var mongoose = require('mongoose');
var co = require('co');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test', {
    server: {
        socketOptions: {
            keepAlive: 1
        }
    }
});

mongoose.connection.on('error', function(err) {
    console.error('MongoDB error: %s', err)
});

co(function*() {
    console.log('starting');
    var schema = new Schema({
        description: {
            type: String,
            required: true
        }
    });
    console.log('creating schema');
    var s = mongoose.model('schema', schema);
    console.log('creating doc');

    var br = new s({
        description: 'abc'
    });

    yield br.save();
}).catch (function (err) {
    console.log('this is the errror -> ', err);
});

Upvotes: 2

Amit
Amit

Reputation: 4353

I'm not seeing Schema being imported from Mongoose!

Have you tried setting the following before creating the new Schema:

var Schema = mongoose.Schema;

Upvotes: 0

Related Questions