In my flutter app, using the file picker, I am trying to upload the file in the mongodb database with nodejs.
The following is the function that i used to send the file to the nodejs backend
void uploadFile(PlatformFile file) async {
var request = http.MultipartRequest('POST',
Uri.parse('$serverURL/files/upload'));
request.files.add(http.MultipartFile.fromBytes(
'file',
File(file.path!).readAsBytesSync(),
filename: file.name,
contentType: MediaType('application', 'pdf'),
));
var response = await request.send();
if (response.statusCode == 200) {
print("File uploaded");
} else {
print("File upload failed");
}
}
I'm connecting with the mongoose database using the connect method
mongoose
.connect(urlApp)
.then(() => server.listen(process.env.PORT || 3000))
.then(() => console.log("Server connected and database is also connected"))
.catch((err) => console.error(err));
Here comes the actual logic of uploading the file
const conn = mongoose.connection;
let gfs;
conn.once("open", () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection("uploads");
});
const urlFile =
"mongodb+srv://<userID>:<password>@docpatientclusteru.lpfrgin.mongodb.net/?retryWrites=true&w=majority";
const storage = GridFsStorage({
url: urlFile,
options: { useNewUrlParser: true, useUnifiedTopology: true },
file: (req, file) => {
return new Promise((resolve, reject) => {
const filename = file.originalname;
const fileInfo = {
filename: filename,
bucketName: "uploads",
};
resolve(fileInfo);
});
},
});
const upload = multer({ storage });
router.post("/upload", upload.single("file"), uploadFile);
whenever i try to call the uploadFile function the flutter app, i get the following error in my nodejs server.
MongoError: (Unauthorized) not authorized on admin to execute command { find: "fs.files", filter: { _id: ObjectID("659b2c1d5e73395e24d9ce58") }, limit: 1, singleBatch: true, batchSize: 1 }
at MongoError.create (C:\Users\Nadoshi\Desktop\yimbs development\Doc Patient App\backend\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\Users\Nadoshi\Desktop\yimbs development\Doc Patient App\backend\node_modules\mongodb-core\lib\cursor.js:212:36)
at C:\Users\Nadoshi\Desktop\yimbs development\Doc Patient App\backend\node_modules\mongodb-core\lib\connection\pool.js:469:18
at process.processTicksAndRejections (node:internal/process/task_queues:77:11)
I tried changing the built-in role from "read and write to any database" to "atlas admin", but the error remained.