如何使用nodejs,expressjs和mongo运行项目

时间:2019-05-24 15:45:15

标签: node.js reactjs mongodb express

安装某些软件包

npm install
npm install mongoose --save
npm install express --save
npm install body-parser

Router.js文件

var Express         = require("express");
var Routes          = Express.Router();
var UserRoute       = require('./src/User/User.Route');
var CommentRoute    = require('./src/Comment/Comment.Route');
Routes.use('/user/', UserRoute);
Routes.use('/comment/', CommentRoute);
module.exports = Routes;    

app.js

const Express       = require("express");
const BodyParser    = require("body-parser");
const Routes        = require("./Routes");
const Cors          = require("cors");

const app = Express();
app.use(Cors());

app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.use('/', Routes);

app.listen(8080, 'localhost', (err) => {
      if(err) {
         console.log(err);
         process.exit(-1);
     }
     console.log("Server listen port 8080");
  });

User.Route.js这是包含user.Route.js的文件

var express     = require('express');
var router      = express.Router();
var Controller  = require('./User.Controller');

router.post('/', (req, res) => {
    Controller.insert(req.body).then(data => {
        res.status(data.status).send({message: data.message});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    })
});


router.put('/:id', (req, res) => {
    Controller.update(req.params.id, req.body).then(data => {
        res.status(data.status).send({message: data.message});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    })
});

router.get('/', (req, res) => {
    Controller.searchAll().then(data => {
        res.status(data.status).send({data: data.data});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    });
});

router.get('/:id', (req, res) => {
    Controller.search(req.params.id).then(data => {
        res.status(data.status).send({data: data.data});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    });
});

router.delete('/:id', (req, res) => {
    Controller.delete(req.params.id).then(data => {
        res.status(data.status).send({message: data.message});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    })
})
module.exports = router;

User.Controller.js

var mongoose        = require('../DBSchema/SchemaMapper');
var UserSchema      = mongoose.model('User');

var UserController = function(){
    this.insert = (data) => {
        return new Promise((resolve, reject) => {
            var user = new UserSchema({
                userName: data.userName,
                password: data.password
            });
            user.save().then(() => {
                resolve({status: 200, message: "Added new user"});
            }).catch(err => {
                reject({status: 500, message: "Error:- "+err});
            })
        })

    }

    this.update = (id, data) => {
        return new Promise((resolve, reject) => {
            UserSchema.update({_id: id}, data).then(() => {
                resolve({status: 200, message: "update user"});
            }).catch(err => {
                reject({status: 500, message: "Error:- " + err});
            })
        })
    }

    this.searchAll = () => {
        return new Promise((resolve, reject) => {
            UserSchema.find().exec().then((data) => {
                resolve({status: 200, data: data});
            }).catch(err => {
                reject({status: 500, message: "Error:- " + err});
            })
        })
    }

    this.search = (id) => {
        return new Promise((resolve, reject) => {
            UserSchema.find({_id:id}).exec().then(user => {
                resolve({status: 200, data: user});
            }).catch(err => {
                reject({status: 500, message: "Error:- " + err});
            })
        })
    }

    this.delete = (id) => {
        return new Promise((resolve, reject) => {
            UserSchema.remove({_id:id}).then(() => {
                resolve({status: 200, message: "remove user"});
            }).catch(err => {
                reject({status: 500, message:"Error:- " + err});
            })
        })
    }
}

module.exports = new UserController();

SchemaMapper.js

var mongoose        = require('mongoose');
const Schema        = mongoose.Schema;

const UserSchema = new Schema({
    userName: {
        type: String,
        require: true
    },
    password: {
        type: String,
        require: true
    }
});

const CommentSchema = new Schema({
    comment: {
        type: String,
        require: true
    },
    date: {
        type: String,
        require: true
    },
    commentBy:[
        {
            type: Schema.Types.ObjectId,
            ref: 'User'
        }
    ]
});

mongoose.model('User', UserSchema);
mongoose.model('Comment', CommentSchema);

mongoose.connect('mongodb://localhost:27017/comments', (err) => {
    if (err) {
        console.log(err);
        process.exit(-1);
    }
    console.log('Connected to the DB');
});

module.exports = mongoose;

Comment.Route.js

var express     = require('express');
var router      = express.Router();
var Controller  = require('./Comment.Controller');

router.post('/', (req, res) => {
    Controller.insert(req.body).then(data => {
        res.status(data.status).send({message: data.message});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    })
});

router.put('/:id', (req, res) => {
    Controller.update(req.params.id, req.body).then(data => {
        res.status(data.status).send({message: data.message});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    })
});

router.get('/', (req, res) => {
    Controller.searchAll().then(data => {
        res.status(data.status).send({data: data.data});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    });
});

router.get('/:id', (req, res) => {
    Controller.search(req.params.id).then(data => {
        res.status(data.status).send({data: data.data});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    });
});

router.delete('/:id', (req, res) => {
    Controller.delete(req.params.id).then(data => {
        res.status(data.status).send({message: data.message});
    }).catch(err => {
        res.status(err.status).send({message: err.message});
    })
});

Comment.Controller.js

var mongoose        = require('../DBSchema/SchemaMapper');
var CommentSchema   = mongoose.model('Comment');

var CommentController = function() {
    this.insert = (data) => {
        return new Promise((resolve, reject) => {
            var comment = new CommentSchema({
                comment: data.comment,
                date: data.date,
                commentBy: data.userId
            });
            comment.save().then(() => {
                resolve({status: 200, message: "Added new comment"});
            }).catch(err => {
                reject({status: 500, message: "Error:- "+err});
            })
        })
    }

    this.update = (id, data) => {
        return new Promise((resolve, reject) => {
            CommentSchema.update({_id: id}, data).then(() => {
                resolve({status: 200, message: "update comment"});
            }).catch(err => {
                reject({status: 500, message: "Error:- " + err});
            })
        })
    }

    this.searchAll = () => {
        return new Promise((resolve, reject) => {
            CommentSchema.find().populate('User').exec().then(data => {
                resolve({status: 200, data: data});
            }).catch(err => {
                reject({status: 500, message: "Error:- " + err});
            })
        })
    }

    this.search = (id) => {
        return new Promise((resolve, reject) => {
            CommentSchema.find({_id: id}).populate('User').exec().then(data => {
                resolve({status: 200, data: data});
            }).catch(err => {
                reject({status: 500, message: "Error:- " + err});
            })
        })
    }

    this.delete = (id) => {
        return new Promise((resolve, reject) => {
            CommentSchema.remove({_id: id}).then(() => {
                resolve({status: 200, message: "remove comment"});
            }).catch(err => {
                reject({status: 500, message:"Error:- " + err});
            })
        })
    }
}

module.exports = new CommentController();

所以我需要知道此代码是否在编码模式的标准中。我想知道这段代码可以在mongoDB服务器上运行

0 个答案:

没有答案