我在特定情況下必須選擇 mongo db 集合中的所有記錄,還要選擇具有特定 Id 的記錄。我了解如何獲取大量記錄,但如何查詢具有特定 ID 的記錄。
app.get('/:id', (req, res) => {
Term.find().sort({ "term": 1 })
.then(result => {
res.render('about', { title: 'About page', terms: result });
})
.catch(err => {
console.log(err);
});
const id = req.params.id;
Term.findById(id)
.then(results => {
res.render('about', { specific: results })
})
});
上面的代碼是否可以正常作業,因為我已經查詢了整個資料庫,Term.find但也可以Term.findbyId(id)
uj5u.com熱心網友回復:
我認為這就是你所需要的,在同一個處理程式中回傳這兩個東西。
app.get("/:id", (req, res) => {
const id = req.params.id;
Term.find()
.sort({ term: 1 })
.then(result =>
Term.findById(id).then(results =>
res.render("about", {
specific: results,
title: "About page",
terms: result
})
)
)
.catch(err => console.log(err));
});
uj5u.com熱心網友回復:
如果您在第一個查詢中選擇所有記錄并從 db 加載所有資料 - 您不需要第二個查詢。您可以使用已從第一次查詢中收到的資料使用純 javascript 執行此操作。
app.get('/:id', (req, res) => {
Term.find().sort({ "term": 1 })
.then(result => {
const specific = result.find(item => item._id.toString() === req.params.id);
res.render('about', {
specific,
title: 'About page',
terms: result
});
})
.catch(err => {
console.log(err);
});
});
如果您不加載所有資料。可能你有一些分頁。您可以同時運行 2 個查詢。
app.get('/:id', (req, res) => {
Promise.all([
Term.find().sort({ "term": 1 }),
Term.findById(req.params.id)
])
.then(values => {
res.render("about", {
title: "About page",
terms: values[0],
specific: values[1]
})
})
.catch(error => console.log(err));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378790.html
上一篇:陣列中元素的索引
