Node.js 如何查找MongoDB集合中的哪些对象包含具有特定信息的字段?
我有一个web应用程序,允许用户打开一个名为“Cruise Ship”的页面。在这个页面上,我希望用户能够看到同一条邮轮上的其他邮轮。我的MongoDB船舶模型以巡航线为场。以下是我的视图控制器的结构:Node.js 如何查找MongoDB集合中的哪些对象包含具有特定信息的字段?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个web应用程序,允许用户打开一个名为“Cruise Ship”的页面。在这个页面上,我希望用户能够看到同一条邮轮上的其他邮轮。我的MongoDB船舶模型以巡航线为场。以下是我的视图控制器的结构: exports.getShip = catchAsync(async (req, res, next) => { const ship = await Ship.findOne({ slug: req.params.slug }).populate({ path: 'revie
exports.getShip = catchAsync(async (req, res, next) => {
const ship = await Ship.findOne({ slug: req.params.slug }).populate({
path: 'reviews',
fields: 'review rating user displayDate ratingsQuantity',
});
const reviewCount = await Review.count();
const allShips = await Ship.find();
if (!ship) {
return next(new AppError('Page does not exist. Please try again.', 404));
}
res.status(200).render('ship', {
title: `${ship.shipName} Reviews`,
ship,
allShips,
reviewCount,
});
});
我尝试包含类似的内容,但它返回未定义:
const cruiseLineInfo = await Ship.find({ cruiseLine: ship.cruiseLine })
在我的尝试中,我希望ship.cruiseLine将被解释为特定船舶页面(例如,“嘉年华邮轮”)的邮轮,然后cruiseLineInfo将包含与查找查询匹配的所有船舶对象。但遗憾的是,它没有奏效。如有任何建议,将不胜感激
我能够使用内联Javascript、一个循环和一个“if”语句在帕格中实现这一点
- var thisCruiseLine = ship.cruiseLine
- var thisShipName = ship.shipName
each ship in allShips
if ship.cruiseLine == thisCruiseLine && ship.shipName != thisShipName
p #{ship.shipName}
在Mongoose中,.find()
只生成查询,但不会立即运行查询。您可以先构建一个查询,然后稍后再运行它
要执行查询,您可以将回调作为参数添加到.find()
或将.exec()
链接到其后面:
const cruiseLineInfo = await Ship.find({ cruiseLine: ship.cruiseLine }, (error, response) => {
// do something with the response
})
在您的情况下,.exec()
似乎更合适:
const cruiseLineInfo = await Ship.find({ cruiseLine: ship.cruiseLine }).exec()