我是Mongoose图书馆的新手。作为一个学习练习,我正在尝试创建一个新记录,从数据库中检索它,记录它,然后关闭数据库连接。我的代码如下:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testdb');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function dbOpenCB(callback) {
console.log('open callback called');
});
const postSchema = mongoose.Schema({
title: String,
body: String,
author: {
name: String
}
});
const Post = mongoose.model('Post', postSchema);
const newPost = new Post({
title: 'foo',
body: 'bar',
author: {
name: 'Joe Blow'
}
});
newPost.save()
.then(function saveCB(newPost) {
console.log('newPost:');
console.dir(newPost);
})
.then(Post.where('title', /f.*/).exec())
.then(function findCB(posts) {
console.log('Posts:');
console.dir(posts);
})
.then(db.close)
.end();
我最终创建记录并记录在saveCB
中,但posts
对象未在findCB
内定义,数据库连接永远不会关闭。
答案 0 :(得分:1)
我不熟悉Mongoose的奇怪承诺API(.end()
是非标准的)。但这应该有效:
var closeDB = db.close.bind(db);
newPost.save()
.then(function saveCB(newPost) {
console.log('newPost:');
console.dir(newPost);
})
.then(function(){
return Post.where('title', /f.*/).exec();
})
.then(function findCB(posts) {
console.log('Posts:');
console.dir(posts);
})
.then(closeDB, closeDB) // always close the db no matter what
.end(); // wtf is this?