简体   繁体   中英

Node.js express download from mongodb

I want to write a rest api, with which i am able to download some data. All datas were stored in a mongodb. I don't know what to pass to the download method, to make it possible.

Here is my current code:

router.get('/download/:productId/:username/:token', function (req, res) {

    var auth = require('../provider/authProvider.js');
    var authInst = new auth();

    authInst.checkAuth(req.params.username, req.params.token, res, function (err, obj) {
        if (obj == true) {
            res.status(200);
            // here is my problem, what to pass to the download-method
            res.download('');
        }
    });        
});

I could not find anything else, than passing paths to the download method.

Does anyone has an idea how to solve my problem?

I assume you know how to set up mongoose environment, putting config, connecting to MongoDB. If not please refer to my answer here .

Now let's say we have a Document in MongoDB as Blog. So we need to create a model for Blog so that we can do CRUD operations using Mongoose ORM.

you need mongoose module for this to be included in your project.

so run this command from your project root directory, it will automatically download mongoose for you. npm install mongoose --save

BlogModel.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BlogSchema = new Schema({
    "title"   : { type: String },
    "user_id" : { type: String },
    "blog_uri" :{ type: String },
    "post_date" : { type : Date, default: Date.now},
    "body" : { type: String, default: '' },
    "comments" : [
                    { 'content'  : { type: String },
                      'user_id'  : { type: String },
                      'comment_date'     : { type: Date },
                      'votes'    : [
                                    {
                                    'user_id' : { type: String }
                                    }
                                   ] 
                    }
                ],
    "hidden" : {type:Boolean, default: false }
});

mongoose.model('Blog', BlogSchema);

So let's create a separate file called BlogController.js where we will write methods for CRUD.

var mongoose = require('mongoose');
var Blog = mongoose.model('Blog');
var ObjectId = require('mongoose').Types.ObjectId;
exports.create = function(req,res){
    var blog = new Blog(req.body);

    blog.save(function(err){
        if(err)
            res.json({message: "Error occured while saving"});
        else{
            res.redirect('/home');
        }    
    });
};

exports.getAll = function(req,res){
    Blog.find(function(err,blogs){
        if(err){
            res.send(err);
        }else{
            res.json(blogs);
        }
    });
};


exports.get = function(req,res){
    var id ;
    try{
        id = new ObjectId(req.params.id);
        Blog.findById(id,function(err,blog){
            if(err){
                res.send(err);
            }else{
                res.render('blog.ejs', {
                    blog: blog
               });
          }
        });
    }catch(e){
        res.send(404);
    }
};


exports.update = function(req,res){
    var id ;
    try{
        id = new ObjectId(req.params.blog_id);
        Blog.findById(id,function(err,blog){
            if(err){
                res.send(err);
            }

            blog.save(function(err){
                if(err)
                    res.send(err);
                 res.render('blog.ejs', {
                    message: "Blog Updated successfully"
                });
            });
        });
    }catch(e){
        res.send(404);
    }
};

exports.delete = function(req,res){
    var id ;
    try{
        id = new ObjectId(req.params.blog_id);
        Blog.remove({_id:id},function(err,blog){
            if(err){
                res.send(err);
            }
               res.render('blog.ejs', {
                    message: "Blog deleted successfully"
                });
        });
    }catch(e){
        res.send(404);
    } 
};

So this was about CRUD using Mongoose. I usually don't use res.render(..) in my projects because i put Templating logic in front end. I just use res.json(..) and pass the json data to the the frontend. So please go ahead and try. I hope i answered your question. You can refer to this repo, for better example. Here i got a very clean CRUD implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM