将图像路径保存到mongodb的方法是什么?

时间:2018-03-14 20:51:54

标签: javascript node.js mongodb rest express

我正在使用nodeJS,express,mongoose等与mongodb一起开发REST API。我正在上传文件并使用multer将其保存到文件夹中。现在我想将文件的路径保存到mongodb文档中。

但是,我使用mongoose架构将数据保存到mongodb。首先我创建了模型。发出请求后,我使用bodyParser(req.body)读取它,并通过创建新实例或更多快捷方式来保存此对象。

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

但是当我使用multer上传文件并希望保存模型的路径时,我无法使用create()函数。那么方法是什么?

3 个答案:

答案 0 :(得分:2)

在 MongoDB 中,我们可以存储单个或多个图像。为了存储多个图像,我使用了 productPictures 数组。

1:首先,创建产品模型

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:创建产品控制器

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:创建产品路径文件

  • 我正在使用 nanoid 为图像生成唯一名称
  • 在src文件夹内创建uploads文件夹
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:创建 server.js 文件

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:最后您可以使用邮递员创建产品 enter image description here

答案 1 :(得分:1)

如果使用multer,您将在std::allocate_shared中获得上传的文件路径,您只需将其保存在数据库中。

答案 2 :(得分:1)

在这里,您可以将图像上传到您想要的某个目的地,这是reference的更多详细信息,包括如何在Mongodb中访问存储的图像,您可以看到有关multer的文档here

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:password@yourinstanced.mlab.com: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);
             });
          });
       });
    }});