Search code examples
node.jsmongodbexpressmongoosemulter

How to upload and retrieve images in mognoose with multer file references


I'm trying to save images in a django style way, where the image gets saved to a folder and the path to the file is returned in a get request.

So far I have the following Picture model:

const PictureSchema = new mongoose.Schema(
  {
    image: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Picture", PictureSchema);

And the following views:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "data/images");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + ".jpg");
  },
});

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

app.post("/upload", upload.single("image"), (req, res) => {
  Picture.create({
    image: req.file.path,
  })
    .then((picture) => res.status(201).json(picture))
    .catch((err) => res.status(500).json({ error: err.message }));
});

app.get("/", (req, res) => {
  Picture.find({}, "-__v")
    .then((pictures) => res.status(200).json(pictures))
    .catch((err) => res.status(500).json({ error: err.message }));
});

Everything works, the file gets saved to a folder and when I retrieve it shows up like:

{
    "_id": "5fd0f1d4f81e3f28b0aa70d3",
    "image": "data\\images\\1607528916952.jpg",
    "createdAt": "2020-12-09T15:48:36.967Z",
    "updatedAt": "2020-12-09T15:48:36.967Z",
    "__v": 0
}

But I have express set up to serve the static directory like:

app.use(express.static("data"));

file screenshot

How do I get it to return the instance with the relative path to the image field instead of the relative path from within the file system?


Solution

  • Since you've defined the data directory to be served statically, you need to request the images using the following url:

    http://<yourHost>:<yourPort>/images/160...44.jpg
    

    If you want to change this and only specify the name of the image, you need to adjust the path you pass to the express.static middleware:

    app.use(express.static("data/images"));
    

    Now you can request the images using the following url:

    http://<yourHost>:<yourPort>/160...44.jpg