Reputation: 1
I am trying to retrieve data from an existing mongodb collection but all I get is an empty array.
I am aware of the pluralization issue so I did specify the collection name in my model, but I'm still receiving an empty array. If I do the same bypassing mongoose and using the MongoClient I do get the results from my collection.
//This is my schema: **
const mongoose = require('mongoose');
// Create schema for nested object
const ownerSchema = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: false }
})
// Create schema for cars collection
const carSchema = new mongoose.Schema({
make: { type: String, required: true },
model: { type: Number, required: true },
owner: { type: ownerSchema, required: false },
colour: { type: String, required: false },
registration: { type: String, required: false },
address: { type: String, required: false }
}, { collection: 'cars' })
let Cars = mongoose.model('Car', carSchema, 'cars');
module.exports = { Cars };
This is the logging to identify that an empty string is returned/same result when I use the endpoint I created on Postman:
Mongoose.connect(URL, clientOptions)
.then(async () => {
console.log('Connected to MongoDB');
try {
const cars = await Cars.find();
console.log('Cars collection contents:', cars);
if (cars.length === 0) {
console.log('No cars found in the Cars collection.');
}
} catch (error) {
console.error('Error checking Cars collection:', error);
}
})
.catch((error) => console.error('Connection to database failed', error));
I always get the output "No cars found in Cars collection."
Instead of getting an empty array back, I should see the documents that are already in the collection.
Upvotes: 0
Views: 29
Reputation: 55
Have you tried in mongosh?
1: use <your_database_name>
2: db.cars.find() || db.<collection_name>.find()
let us know this command's result please.
If this mongosh command returns the data, it might have a problem in your code.
Upvotes: 0