При попытке прочитать изображение из mongoDb я получаю следующую ошибку:
C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\node_modules\mongodb\lib\utils.js:133
throw err;
^TypeError: Cannot read property '_id' of undefined
at new GridReadStream (C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\node_modules\gridfs-stream\lib\readstream.js:43:14)
at Grid.createReadStream (C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\node_modules\gridfs-stream\lib\index.js:53:10)
at gfs.files.findOne (C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\api\controllers\postController.js:118:42)
at result (C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\node_modules\mongodb\lib\operations\execute_operation.js:75:17)
at session.endSession (C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\node_modules\mongodb\lib\operations\execute_operation.js:64:11)
at ClientSession.endSession (C:\CodeWorks\NodeJS\New folder\Parlo-web-backend\node_modules\mongodb\lib\core\sessions.js:135:41)
Мой код:
let gfs;
mongoose.connect(
"mongodb+srv://" +
process.env.MONGO_USER +
":" +
process.env.MONGO_USER_PASSWORD +
"@cluster0-n1cyt.gcp.mongodb.net/" +
process.env.MONGO_DB +
"?retryWrites=true",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
);
const conn = mongoose.connection;
conn.once("open", () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection("uploads");
console.log("imageFileId >>>" + imageFileId);
// working fine till this point, then express server crashes
gfs.files.findOne(
{ _id: mongoose.Types.ObjectId(imageFileId) },
(err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: "No file exists"
});
}
// Check if its an image
if (
file.contentType === "image/jpeg" ||
file.contentType === "image/png"
) {
// Read output to browser
const readstream = gfs.createReadStream(file.filelink);
readstream.pipe(res);
} else {
res.status(404).json({
err: "Not an image"
});
}
}
);
});