我已经在SO上查看了许多答案,但是没有一个能解决我的问题。
我目前正在使用node,express和mongodb创建一个项目。我从种子文件开始,将一些数据放入mongodb:
var products = [
new ProductModel(data),
new ProductModel(data),
new ProductModel(data),
new ProductModel(data),
];
// Connecting to mongodb using mongoose.
mongoose.connect(config.mongodb.dsn, { useNewUrlParser: true })
.then(() => {
console.log("Successfully connected to MongoDB through Mongoose.");
})
.catch((error) => {
console.log("Error when connecting to MongoDB through Mongoose: " + error);
});
// Saving product instances to the product document in mongodb
var done = 0;
for (var i = 0; i < products.length; i++) {
products[i].save((error, result) => {
done++;
if (done == products.length) {
// Disconnecting...
console.log("All products have been loaded into mongodb. Disconnecting now...");
mongoose.disconnect();
}
});
}
然后,我尝试使用以下方法在我的路线文件中检索此数据:
router.get('/', function(req, res, next) {
const products = ProductModel.find();
console.log(products);
res.render('shop/index', { products });
});
但是,我正在console.loging结果在我的终端上,唯一出现的结果是一个查询对象,如下所示:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection:
NativeCollection {
(...)
_traceFunction: undefined,
'$useProjection': true }
我需要在数据库中检索产品。我在做什么错了?
答案 0 :(得分:3)
一切都会执行。 find()
根据文档返回Query
对象:https://mongoosejs.com/docs/api.html#model_Model.find
如果您希望它返回值,只需将其转为等待状态,然后调用exec
即可获得承诺:
router.get('/', async function(req, res, next) {
const products = await ProductModel.find().exec();
console.log(products);
res.render('shop/index', { products });
});