2015-05-22 19 views
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不定,數據庫連接永遠不會關閉。

很明顯,我做錯了什麼。它是什麼?

回答

1

我不熟悉貓鼬的怪異諾言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? 
+0

我現在清楚地看到我的錯誤。謝謝。而'end()'方法是它們的庫的'done()'方法 - http://mongoosejs.com/docs/api.html#promise_Promise-end –