Im in a specific situation where I have to select all records in a mongo db collection but also a record with a specific Id. I understand how to get the whole lot of records but how can I query a record with a specific id as well.
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 })
})
});
would the above code work as I have queried the whole database with Term.find
but also Term.findbyId(id)
CodePudding user response:
I think this is what you need, return both things in the same handler.
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));
});
CodePudding user response:
If you select all records in first query and load all data from db - you don't need a second query. You can do this with plain javascript with data that already received from first query.
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);
});
});
If you don't load all data. Probably you have some paginations. You can run 2 query concurrently.
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));
});