0
我是新來的貓鼬圖書館。作爲一個學習練習,我試圖創建一個新記錄,從數據庫中檢索它,記錄它,然後關閉數據庫連接。我的代碼如下:使用承諾保存,檢索並關閉連接?
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
不定,數據庫連接永遠不會關閉。
很明顯,我做錯了什麼。它是什麼?
我現在清楚地看到我的錯誤。謝謝。而'end()'方法是它們的庫的'done()'方法 - http://mongoosejs.com/docs/api.html#promise_Promise-end –