最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - what is the way of saving image path to mongodb? - Stack Overflow

programmeradmin1浏览0评论

I am developing REST API using nodeJS, express, mongoose etc with mongodb. I am uploading file and saving it to a folder using multer. Now I want to save the path of the file to a mongodb document.

However, I am saving data to mongodb using mongoose schema. First I created the model. When a post request is made, I read it using bodyParser (req.body) and save this object by creating new instance or more shortcut.

Product.create(req.body).then(function(product){
  res.send(product);
}).catch(next);

I am developing REST API using nodeJS, express, mongoose etc with mongodb. I am uploading file and saving it to a folder using multer. Now I want to save the path of the file to a mongodb document.

However, I am saving data to mongodb using mongoose schema. First I created the model. When a post request is made, I read it using bodyParser (req.body) and save this object by creating new instance or more shortcut.

Product.create(req.body).then(function(product){
  res.send(product);
}).catch(next);

But when I am using multer to upload a file and want to save the path to the model I cant do it using create() function. So what is the way ??

Share Improve this question asked Mar 14, 2018 at 20:51 SwadhInSwadhIn 7471 gold badge10 silver badges19 bronze badges 1
  • Please show exactly the code that failed. And trusting the client to send a valid request and directly put that into the db sounds a bit too good. – Jonas Wilms Commented Mar 14, 2018 at 20:56
Add a ment  | 

3 Answers 3

Reset to default 2

In the MongoDB we can store single or multiple images. For storing multiple images I am using productPictures array.

1: First, create the Product model

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true,
      trim: true,
    },
    productPictures: [{ img: { type: String } }],
});

module.exports = mongoose.model('Product', productSchema);

2: Create the product controller

const Product = require('../models/product');

exports.createProduct = (req, res) => {
  const { name} = req.body;

  let productPictures = [];

  if (req.files.length > 0) {
    productPictures = req.files.map((file) => {
      return { img: file.filename };
    });
  }

  const product = new Product({
    name,
    productPictures,
  });

  product.save((error, product) => {
    if (error) return res.status(400).json({ error });
    if (product) {
      res.status(201).json({ product });
    }
  });
};

3: Create products route file

  • I am using nanoid to generate a unique name for images
  • Create uploads folder inside src folder
const express = require('express');
const path = require('path');
const multer = require('multer');
const { nanoid } = require('nanoid');
const { createProduct } = require('../controllers/product');
const router = express.Router();


const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(path.dirname(__dirname), 'uploads'));
  },
  filename: function (req, file, cb) {
    cb(null, nanoid() + '-' + file.originalname);
  },
});


const upload = multer({ storage: storage });

router.post(
  '/products/create',
  upload.array('productPicture'), // for storing single image : upload.single('productPicture')
  createProduct
);

module.exports = router;

4: Create server.js file

const env = require('dotenv');
const express = require('express');
const mongoose = require('mongoose');
const app = express();

// routes
const productRoutes = require('./routes/product');

env.config();

mongoose
  .connect(`${process.env.MONGO_URI}`, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() => {
    console.log('Database connected');
  });

// Body parser (You can you **body-parser**)
app.use(express.json());

app.use('/api', productRoutes);

app.listen(process.env.PORT, () => {
  console.log(`Server is running on port ${process.env.PORT}`);
});


5: Finally you can create product using postman

Here you can upload the image into some destination you want, this is for the reference for more details information including how to access stored images in Mongodb and you can see the documentation here about multer.

express = require('express')
   , router = express.Router()
   , MongoClient = require('mongodb').MongoClient
   , ObjectId = require('mongodb').ObjectId
   , fs = require('fs-extra')
   // Your mongodb or mLabs connection string
   , url = 'mongodb://username:[email protected]:29459/yourdb'
   , multer = require('multer')
   , util = require('util')
   , upload = multer({limits: {fileSize: 2000000 },dest:'/uploads/'})

app.post('/profile', upload.single('avatar'), function (req, res, next) { 
   // req.file is the `avatar` file
   // req.body will hold the text fields, if there were any
        if (req.file == null) {
       // If Submit was accidentally clicked with no file selected...
    )} else { 
       MongoClient.connect(url, function(err, db){
       // this landing will give you any option of file information that you can collect
        console.log('landing here', req.file)
       // read the img file from tmp in-memory location
       var newImg = fs.readFileSync(req.file.path);
       // encode the file as a base64 string.
       var encImg = newImg.toString('base64');
       // define your new document
       var newItem = {
          contentType: req.file.mimetype,
          size: req.file.size,
          name: req.file.originalname,
          path: req.file.path
       };
    db.collection('yourcollectionname')
       .insert(newItem, function(err, result){
       if (err) { console.log(err); };
          var newoid = new ObjectId(result.ops[0]._id);
          fs.remove(req.file.path, function(err) {
             if (err) { console.log(err) };
             res.send(newItem);
             });
          });
       });
    }});

If using multer you will get uploaded files path in req.file.path and you just need to save that in your database.

发布评论

评论列表(0)

  1. 暂无评论