Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //******* users.js: ********//
- var express = require('express');
- var router = express.Router();
- var mongoose = require('mongoose');
- var User = mongoose.model('User');
- /* When accessing http://localhost:3000/users/ */
- router.route('/')
- // create a user (accessed at POST http://localhost:3000/users/)
- .post(function (req, res) { // create a new instance of the User model
- new User({ // set the user's attributes (comes from the request)
- firstname: req.body.firstname,
- lastname: req.body.lastname,
- age: req.body.age,
- update_at: Date.now()
- })
- .save(function (err) {
- if (err)
- res.send(err);
- res.json({message: 'User created!'});
- });
- })
- // get all the users (accessed at GET http://localhost:8080/api/users)
- .get(function (req, res) {
- User.find(function (err, users) {
- if (err)
- res.send(err);
- res.json(users);
- });
- });
- /* When accessing http://localhost:3000/users/:userId */
- router.route('/:userId')
- // get the user with that id (accessed at GET http://localhost:3000/users/:userId)
- .get(function (req, res) {
- User.findById(req.params.userId, function (err, user) {
- if (err)
- res.send(err);
- res.json(user);
- });
- })
- // update the user with this id (accessed at PUT http://localhost:3000/users/:userId)
- .put(function (req, res) {
- //use our user model to find the user we want
- User.findById(req.params.userId, function (err, user) {
- if (err) res.send(err);
- if (!!req.body.firstname)
- user.firstname = req.body.firstname;
- if (!!req.body.lastname)
- user.lastname = req.body.lastname;
- if (!!req.body.age)
- user.age = req.body.age;
- // save the user
- user.save(function (err) {
- if (err)
- res.send(err);
- res.json({message: 'User successfully updated!'});
- });
- });
- })
- // delete the user with this id (accessed at DELETE http://localhost:3000/users/:userId)
- .delete(function (req, res) {
- User.remove({ _id: req.params.userId }, function (err, user) {
- if (err)
- res.send(err);
- res.json({message: 'Successfully deleted'});
- });
- });
- module.exports = router;
- //******* userDB.js: ********//
- var mongoose = require('mongoose');
- var Schema = mongoose.Schema ;
- var User = new Schema({
- firstname: String,
- lastname: String,
- age: Number,
- update_at: Date
- });
- mongoose.model('User', User);
- mongoose.connect('localhost', 'MyNodeDB');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement