0

我在想应该有一个fs.files.findAll()这样我就可以获取所有文件名并将其显示在页面上。现在我一次只能找到一个,我可以展示它们。我想要一个包含数据库中所有图像的索引页。

const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
const fs = require("fs");
const express = require("express");
const app = express("/")
mongoose.connect("mongodb://localhost/newDb");
const conn = mongoose.connection;

app.set("view engine", "ejs"); // set the view engine
app.use(express.static("public"));

const uploadImages = require("./uploadImages");
const getAllImages = require("./getAllImages");



console.log(mongoose.connection.readyState);

app.get("/:img", (req, res) => {
    getAllImages(conn, req.params.img, res)
})

app.get("/", (req, res) => {
    //render all images on page
    //how do I find how many images are in the DB
    //and to get the file names to pass to ejs
    //so I could do forloop to get // img src "/image1.jpg"
})

app.listen(3000, (err) => {
    console.log("listening on port 3000")
})

在 getAllImages

const mongoose = require("mongoose");
const Grid = require("gridfs-stream");
const fs = require("fs")
function getAllImages(conn, img, response){
    const gfs = Grid(mongoose.connection.db, mongoose.mongo);
    const readStream = gfs.createReadStream({
        filename :img
    })
    readStream.on("error" , function(err){
        console.log("An error: ", err);
    })
    readStream.pipe(response);
    // mongoose.connection.db.listCollections( (err, names) => {
    //     console.log(names);
    // })


}
module.exports = getAllImages;
4

1 回答 1

0

我是这样做的:

const Schema = mongoose.Schema;
const Image = mongoose.model("Image",
            new Schema({filename : String, contentType : String, uploadDate : Date}),
            "fs.files"
            );

然后

app.get("/", (req, res) => {
    Image.find()
        .then((docs) =>{
            var imageNames = docs.map((e) => {
                return e.filename
            })
            res.render("index", {
                imageNames
            })
            console.log(docs)
        })
})

在索引中

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>index</title>
    </head>
    <body>
        <h1>Hello</h1>
        <% imageNames.forEach((e) =>{ %>
            <a href = <%=e %>><%=e.split(".")[0]%></a>
            <img src = "/<%=e%>"> <br>
        <%})%>
    </body>
</html>

我不想设置猫鼬模式。我听说猫鼬需要那个。还有另一种使用gridf-stream的方法吗?

于 2017-02-11T21:47:28.227 回答