Bạn có chắc chắn muốn xóa bài viết này không ?
Bạn có chắc chắn muốn xóa bình luận này không ?
NodeJS – use Mongoose to save Files/Images to MongoDB
https://grokonez.com/node-js/nodejs-use-mongoose-to-save-files-images-to-mongodb
NodeJS – use Mongoose to save Files/Images to MongoDB
In the tutorial, we will show how to build a NodeJS application to save files/images to MongoDB database using Mongoose.
Related posts:
Mongoose save files/images to MongoDB
Firstly, we define a Mongoose model for files/images with Buffer data as below:
const ImageSchema = mongoose.Schema({
type: String,
data: Buffer
});
To read/write data of file/image, we use fs.readFileSync('/path/to/file')
and fs.writeFileSync('/path/to/file', image.data)
functions of NodeJS file-system module.
Below segment code is used to store file/image to MongoDB:
// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
// empty the collection
Image.remove(err => {
if (err) throw err;
console.log("Removed all documents in 'images' collection.");
var imageData = fs.readFileSync('/path/to/file');
// Create an Image instance
const image = new Image({
type: 'image/png',
data: imageData
});
// Store the Image to the MongoDB
image.save()
.then(img => {
// Find the stored image in MongoDB, then save it in a folder
Image.findById(img, (err, findOutImage) => {
if (err) throw err;
try{
fs.writeFileSync('/path/to/file', findOutImage.data);
}catch(e){
console.log(e);
}
});
});
})
})
Practice
We build a NodeJS project as below structure:
More at:
https://grokonez.com/node-js/nodejs-use-mongoose-to-save-files-images-to-mongodb
NodeJS – use Mongoose to save Files/Images to MongoDB





