我正在尝试将mongoose
与es6
一起使用,但以下代码没有运气:
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();
});
输出只是'开始'并永远挂在那里。
任何人都可以为我解决这个问题吗?
答案 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);
});