[英]mongoose equivalent to a mongoDB query
我正在遵循一個簡單的教程 。
問題是,我使用的是momngoose而不是Mongo。 在達到這一點之前,我沒有任何問題:
app.get('/', (req, res) => {
db.collection('quotes').find().toArray((err, result) => {
if (err) return console.log(err)
// renders index.ejs
res.render('index.ejs', {quotes: result})
})
})
這樣,可以訪問引號並在index.ejs上進行操作
現在,我嘗試這樣做:
app.get('/theroute', (req, res) => {
MyMongoModel.find()
.then(documents => {
res.render('index.ejs', *not entirely sure on what to put here*)
})
});
但是當我嘗試使用index.ejs頁面上的文檔時,得到了“未定義”的結果。
就是這樣。 不確定如何使用Google或應該怎么做。
謝謝!
請嘗試以下操作:
MyMongoModel.find({}, (err, foundQuotes) => {
if(err) return console.log(err);
res.render('index.ejs', {quotes: foundQuotes});
}
傳遞給find()
的第一個參數{}
將檢索與特定模型匹配的所有數據庫條目,並將該集合作為foundQuotes
傳遞給回調函數( find()
的第二個參數)。
在回調函數中,呈現index.ejs
(如果沒有錯誤),並將foundQuotes
分配給一個稱為quotes
的變量。 這樣就可以在index.ejs
文件中訪問quotes
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.