mongoose es6对我不起作用

时间:2015-06-26 17:18:34

标签: mongodb mongoose ecmascript-6

我正在尝试将mongoosees6一起使用,但以下代码没有运气:

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();
});

输出只是'开始'并永远挂在那里。

任何人都可以为我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

以防有人遇到同样的问题。使用co你总是应该抓住错误,如果不是你就不会知道它有什么问题。代码工作的示例。

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);
});