我在 MongoDB 上有一个集合,我正在尝试使用 find()
从中查询所有元素:
const mongoose = require('mongoose');
const Featured = mongoose.model('featured');
module.exports = app => {
app.get('/api/featured', async (req, res) => {
console.log("featured route");
const featured = await Featured.find();
console.log(featured);
res.send(featured);
})
}
这是 Featured.js:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({});
mongoose.model('featured', featuredSchema);
但是,我在提出请求时遇到错误:
(node:75568) UnhandledPromiseRejectionWarning: MongooseError: Operation `featureds.find()` buffering timed out after 10000ms
at Timeout.<anonymous> (/Users/prikshetsharma/Desktop/humboiserver/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(node:75568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
如何修复此错误并使所有集合项以 find()
返回?奇怪的是,错误显示 featureds.find()
而我从来没有在我的代码中的任何地方使用过特色词。
答案 0 :(得分:0)
快速修复:
Featured.js
中导出模型:const mongoose = require('mongoose');
const { Schema } = mongoose;
const featuredSchema = new Schema({}, { collection: "featured" });
module.exports = mongoose.model('featured', featuredSchema);
const mongoose = require('mongoose');
// correct this path to your original path of Featured.js
const Featured = require('./Featured.js');
app.get('/api/featured', async (req, res) => {
try {
console.log("featured route");
const featured = await Featured.find();
console.log(featured);
res.send(featured);
}
catch(e) {
console.log('Catch an error: ', e)
}
});
featureds.find()
缓冲在 10000 毫秒后超时,答案 1 :(得分:0)
对于可能偶然发现此问题的其他任何人:我的问题与错误连接有关,我设法通过使用 mongoose.connect
而不是 mongoose.createConnection
来修复它。
请注意Mongoose documentation saying:
<块引用>默认情况下,如果您使用没有连接的模型,Mongoose 不会抛出任何错误。
...这只会导致缓冲超时。