我已经在这里看到过这个问题很多次,但没有一个解决方案适合我。这是代码:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var db = mongoose.connection;
var dbUrl = 'mongodb://george:paradamodei123@ds037234.mongolab.com:37234/mydb';
var perosonSchema = new Schema({
id: Number,
name: String,
age: Number,
stories: [{type: Schema.Types.ObjectId, ref: "Story"}]
});
var storySchema = new Schema({
_creator: {type: Number, ref: "Person"},
title: String,
fans: [{type: Number, ref: "Person"}]
});
var Story = mongoose.model("Story", storySchema);
var Person = mongoose.model("Person", perosonSchema);
db.on('error', function () {
console.log('there was an error communicating with the database');
});
mongoose.connect(dbUrl);
console.log('connected!');
var aaron = new Person({id: 0, name: "Aaron", age: 32});
console.log("created aaron");
aaron.save(function(err) {
console.log("no error");
var story1 = new Story({
title: "Once upon a time",
_creator: aaron.id
});
story1.save(function (err){
if(err) return console.log("err");
});
});
console.log("finished");
db.close();
process.exit();
所以,当我运行脚本时,它记录它连接,它创建了aaron,SKIPS"没有错误"并且只记录"已完成"。值得一提的是,我是mongoose和节点的完全开始,所以很抱歉,如果这是一个简单的问题,但我无法弄明白。
答案 0 :(得分:0)
这是因为aaron.save是asyncron调用,它调用,但是你的程序不等待响应,只是继续工作,并退出进程。当亚伦得救时,过程就会退出; 要修复它,只需在回调函数中调用finished和db.close 像这样的东西
aaron.save(function(err) {
console.log("no error");
var story1 = new Story({
title: "Once upon a time",
_creator: aaron.id
});
story1.save(function (err){
if(err) return console.log("err");
console.log("finished");
db.close();
process.exit();
});
});
这样你的代码就可以节省aaron。保存后将创建故事,保存并保存关闭数据库并退出进程
了解更多关于nodejs回调的信息here