我在想应该有一个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;
答案 0 :(得分: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的方法吗?