mongodb 如何解决文件上传显示错误

92dk7w1h  于 2023-01-20  发布在  Go
关注(0)|答案(1)|浏览(216)

我是初学者谁试图学习nodejs和mongodb通过学习登录注册注销..最近我试图添加功能的文件上传,但它显示这样的错误.

22|         </thead>
    23|         <tbody>
 >> 24|             <% for(var i=0; i < data.length > 0; i++) {%>
    25|              <tr>
    26|                 <td><%= data[i].filespath %></td>
    27|                  <td>

data is not defined

我正在把我的项目注册登录功能和文件加载功能结合起来,但是它不起作用。我想知道是什么问题。有人能帮我检查一下代码,指出我做错了什么吗?
这是我的服务器. js

// using express JS
var express = require("express");
var app = express();

// express formidable is used to parse the form data values
var formidable = require("express-formidable");
app.use(formidable());

// use mongo DB as database
var mongodb = require("mongodb");
var mongoClient = mongodb.MongoClient;

// the unique ID for each mongo DB document
var ObjectId = mongodb.ObjectId;

// receiving http requests
var httpObj = require("http");
var http = httpObj.createServer(app);

// to encrypt/decrypt passwords
var bcrypt = require("bcrypt");

// to store files
var fileSystem = require("fs");

const bodyParser = require('body-parser');
const multer = require('multer');
const mongoose = require('mongoose');
const path = require('path');

// to start the session
var session = require("express-session");
app.use(session({
    secret: 'secret key',
    resave: false,
    saveUninitialized: false
}));

// define the publically accessible folders
app.use("/public/css", express.static(__dirname + "/public/css"));
app.use("/public/js", express.static(__dirname + "/public/js"));
app.use("/public/img", express.static(__dirname + "/public/img"));
app.use("/public/font-awesome-4.7.0", express.static(__dirname + "/public/font-awesome-4.7.0"));
app.use("/public/fonts", express.static(__dirname + "/public/fonts"));


const filePath = path.resolve(__dirname,'public');

app.use(express.static(filePath));

app.use(bodyParser.urlencoded({extended:false}))

// using EJS as templating engine
app.set("view engine", "ejs");

// main URL of website
var mainURL = "http://localhost:3000";

// global database object
var database = null;

// app middleware to attach main URL and user object with each request
app.use(function (request, result, next) {
    request.mainURL = mainURL;
    request.isLogin = (typeof request.session.user !== "undefined");
    request.user = request.session.user;

    // continue the request
    next();
});



// start the http server
http.listen(3000, function () {
    console.log("Server started at " + mainURL);

    // connect with mongo DB server
    mongoClient.connect("mongodb://localhost:27017", {
        useUnifiedTopology: true
    }, function (error, client) {

        // connect database (it will automatically create the database if not exists)
        database = client.db("file_transfer");
        console.log("Database connected.");

        // logout the user
        app.get("/Logout", function (request, result) {
            request.session.destroy();
            result.redirect("/");
        });

        // show page to login
        app.get("/Login", function (request, result) {
            result.render("Login", {
                "request": request
            });
        });

        // authenticate the user
        app.post("/Login", async function (request, result) {
            var email = request.fields.email;
            var password = request.fields.password;

            var user = await database.collection("users").findOne({
                "email": email
            });

            if (user == null) {
                request.status = "error";
                request.message = "Email does not exist.";
                result.render("Login", {
                    "request": request
                });
                
                return false;
            }

            bcrypt.compare(password, user.password, function (error, isVerify) {
                if (isVerify) {
                    request.session.user = user;
                    result.redirect("/");

                    return false;
                }

                request.status = "error";
                request.message = "Password is not correct.";
                result.render("Login", {
                    "request": request
                });
            });
        });

        // register the user
        app.post("/Register", async function (request, result) {

            var name = request.fields.name;
            var email = request.fields.email;
            var password = request.fields.password;
            var reset_token = "";
            var isVerified = true;
            var verification_token = new Date().getTime();

            var user = await database.collection("users").findOne({
                "email": email
            });

            if (user == null) {
                bcrypt.hash(password, 10, async function (error, hash) {
                    await database.collection("users").insertOne({
                        "name": name,
                        "email": email,
                        "password": hash,
                        "reset_token": reset_token,
                        "uploaded": [],
                        "sharedWithMe": [],
                        "isVerified": isVerified,
                        "verification_token": verification_token
                    }, async function (error, data) {

                        request.status = "success";
                        request.message = "Signed up successfully. You can login now.";

                        result.render("Register", {
                            "request": request
                        });
                        
                    });
                });
            } else {
                request.status = "error";
                request.message = "Email already exist.";

                result.render("Register", {
                    "request": request
                });
            }
        });

        // show page to do the registration
        app.get("/Register", function (request, result) {
            result.render("Register", {
                "request": request
            });
        });

        // home page
        app.get("/", function (request, result) {
            result.render("index", {
                "request": request
            });

            const fileSchema = new mongoose.Schema({
                filespath:String
            })
            
            
            const fileModel = mongoose.model('filesdemo',fileSchema)
        
            app.get('/',(req,res)=>{
                fileModel.find((err,data)=>{
                         if(err){
                             console.log(err)
                         }
                        if(data){
                            console.log(data)
                            res.render('index',{data:data})
                        } 
                       else{
                           res.render('index',{data:{}})
                       } 
                })
                
            })
            
            app.post('/',upload.single('file'),(req,res)=>{
                const x= 'uploads/'+req.file.originalname;
                const files = new fileModel({
                    filespath:x
                })
                files.save((err,data)=>{
                     if(err){
                         console.log(err)
                     }
                     else{
                         console.log('data',data)
                        res.redirect('/')
                     }
                })
            })
            
            app.get('/download/:id',(req,res)=>{
                 fileModel.find({_id:req.params.id},(err,data)=>{
                     if(err){
                         console.log(err)
                     } 
                     else{
                        const path= __dirname+'/public/'+data[0].filespath;
                        res.download(path);
                     }
                 })
            })
            
            app.get('/delete/:id', (req, res) => {
                fileModel.find({_id: req.params.id}, (err, data) => {
                    if(err) {
                        console.log(err);
                        res.send(err);
                    } else {
                        const path= __dirname+'/public/'+data[0].filespath;
                        fs.unlink(path, (err) => {
                            if (err) throw err;
                            console.log(path + ' was deleted');
                        });
            
                        fileModel.deleteOne({ _id: req.params.id }, (err) => {
                            if (err) {
                                console.log(err);
                                res.send(err);
                            } else {
                                console.log('File deleted successfully');
                                res.send('File deleted successfully');
                            }
                        });
                    }
                });
            });
                    

        });
    });
});

这是我的视图/index.ejs,作为主页

<%- include ("includes/header") %>

<center>
    <h2>Upload Files</h2>
    <form action="/" method="POST" enctype="multipart/form-data">
     <input type="file" name="file"><br>
     <input type="submit" value="Upload">
    </form><br><br><br><br>
</center>
<h2>Download Files</h2>
    <table>
        <thead>
            <tr>
                <td>
                    image
                </td>
                <td>
                    download
                </td>
            </tr>
        </thead>
        <tbody>
            <% for(var i=0; i < data.length > 0; i++) {%>
             <tr>
                <td><%= data[i].filespath %></td>
                 <td>
                     <form action="/download/<%= data[i]._id %>" method="GET">
                      <input type="submit" value="Download">
                    
                    <form action="/delete/<%= data[i]._id %>" method="GET">
                        <input type="submit" value="Delete">
                      </form>
                 </td>
             </tr>
            <% } %>

        
        </tbody>
    </table>
<%- include ("includes/footer") %>

我很抱歉,如果代码有点混乱,因为我仍然是初学者试图学习。这意味着很多我,如果你能帮助我与此。谢谢了很多。

mspsb9vt

mspsb9vt1#

根据mongoose的API文档,find调用的第一个参数应该是查询。
因此,代替:

fileModel.find((err,data)=>{

我觉得你想要的是:

fileModel.find({}, (err, data) => {

这将返回所有文档,因为传递空对象{}意味着执行搜索查询,而不限制MongoDB。
希望这有帮助:)

相关问题