2015-08-13 59 views
0

我很新,節點和續集,我試圖按照這short introduction爲什麼我的Model.find不返回任何內容?

我已經完成了連接到我的數據庫的部分(postgres)。我也定義了一個模型:

var User = sequelize.define('User', { 
    username: Sequelize.STRING, 
    password: Sequelize.STRING 
}); 

我已經成功地同步了方案和創建的實例。但是,當我嘗試使用這個數據庫中讀取:

User 
    .find({ where: { username: 'john-doe' } }) 
    .then(function(err, johnDoe) { 
    if (!johnDoe) { 
     console.log('No user with the username "john-doe" has been found.'); 
    } else { 
     console.log('Hello ' + johnDoe.username + '!'); 
     console.log('All attributes of john:', johnDoe.get()); 
    } 
    }); 

該實例確實存在,但我只看到消息「與......沒有用戶」。它生成的查詢似乎是正確的,當我手動嘗試時,返回的結果是我期望看到的。

使用相同的查詢,我可以做到這一點,這也適用:

sequelize.query("SELECT * FROM my_user_table where username='john-doe'", { type: sequelize.QueryTypes.SELECT}) 
    .then(function(items) { 
    // We don't need spread here, since only the results will be returned for select queries 
    console.log(items); 
    }); 

缺少什麼我在這裏?

回答

1

其實你太靠近了。但是,您不能在then方法中使用參數進行錯誤處理。

所以你必須像下面一樣使用;

User 
    .findOne({ where: { username: 'john-doe' } }) 
    .then(function(johnDoe) { 
    if (!johnDoe) { 
     console.log('No user with the username "john-doe" has been found.'); 
    } else { 
     console.log('Hello ' + johnDoe.username + '!'); 
     console.log('All attributes of john:', johnDoe.get()); 
    } 
    }); 
+0

Gotcha。非常感謝 –

1

您在混合承諾和節點式回調。通常,當您將回調傳遞給原始函數時,您只希望得到(err, results)。如果你打電話給then,你正在承諾並且只能期待結果。您應該致電catch以獲取任何錯誤。

User 
    .find({ where: { username: 'john-doe' } }) 
    .then(function(johnDoe) { 
    if (!johnDoe) { 
     console.log('No user with the username "john-doe" has been found.'); 
    } else { 
     console.log('Hello ' + johnDoe.username + '!'); 
     console.log('All attributes of john:', johnDoe.get()); 
    } 
    }) 
    .catch(function(err) { 
    // Error handling here 
    }); 
+0

謝謝,spot on。接受第一個也是正確的答案 –

相關問題