我正在尝试从现有的 mongodb 集合中检索数据,但我得到的只是一个空数组。
我知道复数问题,因此我在模型中指定了集合名称,但我仍然收到一个空数组。如果我绕过 mongoose 并使用 MongoClient 做同样的事情,我确实会从我的集合中得到结果。
//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 };
这是当我使用在 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));
我总是得到输出“在汽车集合中找不到汽车。”
我应该看到集合中已有的文档,而不是返回一个空数组。
你尝试过mongosh吗?
1:使用
2: db.cars.find() || db.
请让我们知道此命令的结果。
如果此 mongosh 命令返回数据,则您的代码可能有问题。