Reputation: 85
I have already looked at many answers here at SO, but none of them solved my problem.
I'm currently creating a project using node, express, and mongodb. I started with a seeder file to put some data into 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();
}
});
}
Then, I am trying to retrieve this data in my routes file, using:
router.get('/', function(req, res, next) {
const products = ProductModel.find();
console.log(products);
res.render('shop/index', { products });
});
However, I am console.logging the result on my terminal, and the only result that comes up is a query object that looks like this:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map {}, _posts: Map {} },
_executionCount: 0,
mongooseCollection:
NativeCollection {
(...)
_traceFunction: undefined,
'$useProjection': true }
I needed to retrieve the products in my db. What am I doing wrong?
Upvotes: 1
Views: 667
Reputation: 475
Everything is executed as it should. find()
returns a Query
object as per the docs: https://mongoosejs.com/docs/api.html#model_Model.find
If you want it to return the value, just turn it to an await and call exec
to get a promise:
router.get('/', async function(req, res, next) {
const products = await ProductModel.find().exec();
console.log(products);
res.render('shop/index', { products });
});
Upvotes: 3