我有这个node.js代码,它将一组文本数组保存到mongolab.com上托管的MongoDB中。我使用Mongoose ORM并注意代码连接到数据库但是没有执行save方法。
function save2Db(texts) {
var db = require('mongoose');
db.Promise = global.Promise;
db.connect('mongodb://user:pswd@ds013456.mlab.com:13456/heroku_xxxxxxx');
db.connection.on('error', console.error.bind(console, 'connection error!'));
db.connection.on('close', console.error.bind(console, 'closed db!'));
db.connection.once('open', function() {
console.log('opened db!');
/* Create schema */
var textSchema = new db.Schema({
date: { type: Date, default: Date.now },
text: [String]
});
/* Create model */
var TextModel = db.model('Text', textSchema, 'testCollection');
/* Save data to database */
texts.forEach(function(content) {
console.log(`saving ${content}`);
var t = new TextModel({text : content});
t.save(function (err) {
console.log('inside t.save');
if (err) {
console.error(err);
} else {
console.log('Saved to db');
}
}); //t.save
}); // texts.forEach
db.connection.close();
});
}
save2Db([['a','b'],['c'],['d','e','f','g']])
获取输出
opened db!
saving a,b
saving c
saving d,e,f,g
closed db!
你知道为什么save方法不起作用吗?谢谢。
答案 0 :(得分:1)
t.save
是一个异步函数。您正在关闭数据库的连接,然后才能运行保存。如果要关闭数据库连接,则需要等到所有保存回调都被调用。我建议使用promises。
function save2Db(texts) {
var db = require('mongoose');
db.Promise = global.Promise;
db.connect('mongodb://user:pswd@ds013456.mlab.com:13456/heroku_xxxxxxx');
db.connection.on('error', console.error.bind(console, 'connection error!'));
db.connection.on('close', console.error.bind(console, 'closed db!'));
db.connection.once('open', function() {
console.log('opened db!');
/* Create schema */
var textSchema = new db.Schema({
date: {
type: Date,
default: Date.now
},
text: [String]
});
/* Create model */
var TextModel = db.model('Text', textSchema, 'testCollection');
/* Save data to database */
var saves = [];
texts.forEach(function(content) {
console.log(`saving ${content}`);
var t = new TextModel({
text: content
});
saves.push(t.save());
});
Promise.all(saves)
.then(() => db.connection.close())
.catch(err => {
console.log(err);
db.connection.close();
});
});
}
一些附加说明:您应该将数据库启动部分移出save2Db
函数,因为每次要保存时都会调用它。您也不必等到连接打开,因为您的猫鼬模型无论如何都会这样做。最后但同样重要的是:如果您一直在进行数据库连接,则不需要连接和关闭数据库连接。只需连接一次,然后将其打开。