我有文件要通过mongoose向mongo添加数据:
var mongoose = require('mongoose');
var mongoDB = 'mongodb://myuser:mypass@ds145293.mlab.com:45293/employees';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open',function(){
console.log('connected')
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
});
})
mongoose.connection.close()
从猫鼬站点几乎逐字复制。我能够连接到数据库,但是我没有第二个控制台日志。我有数据库但没有集合。这是问题吗?
答案 0 :(得分:1)
将mongoose.Schema
替换为new Schema
,我也不认为此mongoose.Promise = global.Promise
是必需的。
答案 1 :(得分:0)
在关闭数据库之前无法完成保存。有很多选项可以等待保存。我喜欢异步/等待。
编辑:对不起,那太快了。更新了示例。
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
async function run() {
await mongoose.connect(mongoDB);
console.log('connected')
var kittySchema = new mongoose.Schema({ name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
await fluffy.save();
console.log('saved');
mongoose.connection.close();
}
run();
或者您也可以在保存后将其移到附近:
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost/something';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once('open', function () {
console.log('connected')
var kittySchema = new mongoose.Schema({name: String });
var Kitten = mongoose.model('Kitten', kittySchema);
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
console.log('saved');
mongoose.connection.close();
});
})