是否可以在nodejs中使用mongodb的两个select语句



我处于一种特定的情况,我必须选择mongo数据库集合中的所有记录,但也必须选择具有特定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.findTerm.findbyId(id)查询整个数据库一样工作吗

我认为这就是您所需要的,在同一个处理程序中返回这两个东西。

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));
});

如果在第一个查询中选择所有记录并从数据库加载所有数据,则不需要第二个查询。您可以使用已从第一个查询中接收到的数据的纯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));
});

最新更新