删除按钮随机工作

时间:2018-02-13 14:52:51

标签: express

我是新来的表达,我能够让大部分工作直到我想创建一个删除按钮。

我无法让我的删除按钮一直工作。它在随机时刻工作,有时则不起作用,当它不起作用时,会出现以下错误:

{CastError:施放到ObjectId的值失败"未定义"在路径" _id"对于模型"用户"

以下代码:

Both index.js and users.js files are in routes directory



//user - file in module directory
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

var UserSchema = mongoose.Schema({
  username: {
    type: String,
    index: true
  },
  password: {
    type: String
  },
  email: {
    type: String
  },
  name: {
    type: String
  },
  isAdmin: {
    type: Boolean,
    default: false
  }
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(newUser.password, salt, function(err, hash) {
          newUser.password = hash;
          newUser.save(callback);
      });
    });
}

module.exports.getUserByUsername = function(username, callback){
  var query = {username: username};
  User.findOne(query, callback);
}

module.exports.getUserById = function(id, callback){
  User.findById(id, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback){
  bcrypt.compare(candidatePassword, hash, function(err, isMatch){
    if(err) throw err;
    callback(null, isMatch);
  });
}






<!--page with delete button-->
<section class="jumbotron">
      <div class="container">
        <h1 class="jumbotron-heading text-center">Users Page</h1>
      </div>
      <div>
        <ul class="list-group">
          {{#each users}}
            <li class="list-group-item"><a href="/users/user/{{_id}}">{{this.name}}</a></li>
          {{/each}}
        </ul>
      </div>
</secion>
&#13;
&#13;
&#13;

&#13;
&#13;
//main.js  - file in the javascript directory
$(document).ready(function(){
   $('.delete-user').on('click', function(e) {
       $target = $(e.target);
       const id = $target.attr('data-id');
       $.ajax({
          type: 'DELETE',
          url: '/users/user/'+id,
          success: function(response){
              alert('Deleting User');
              window.location.href='/users/users';
          },
          error: function(err){
              console.log(err);
          }
      });
   });
});
&#13;
&#13;
&#13;

&#13;
&#13;
//users.js - file
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var User = require('../modules/user');

// Admin Page
router.get('/admin', function(req, res){
  res.render('admin');
});

// Login Page
router.get('/login', function(req, res){
  res.render('login');
});

// Registeration Page
router.get('/register', function(req, res){
  res.render('register');
});

// Users
router.get('/users', function(req, res) {
  User.find({}, function(err, users) {
    if(err) {
      console.log(err);
    } else {
      res.render('users', {
        users: users
      });
    }
  });
});

// Individual Users
router.get('/user/:id', function(req, res) {
  User.findById(req.params.id, function(err, users) {
    res.render('user', {
      users: users
    });
  });
});

// Delete Users
router.delete('/user/:id', function(req, res) {
  let query = {_id:req.params.id};

   User.remove(query, function(err){
       if(err){
           console.log(err);
       }
      res.send('Success');
  });
});

// Create post request from form to server
router.post('/register', function(req, res){
  var name = req.body.name;
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  var password2 = req.body.password2;
  var adminCode = req.body.adminCode;

//Validation
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('email', 'Email is Required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if(errors){
  res.render('register',{
    errors:errors
  });
} else {
  var newUser = new User({
    name: name,
    email: email,
    username: username,
    password: password
  });

  if(adminCode === 'secretcode123') {
    newUser.isAdmin = true;
  }

User.createUser(newUser, function(err, user){
  if(err) throw err;
  console.log(user);
});

req.flash('success_msg', 'You are registered and can now login');

res.redirect('/users/register');

}
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.getUserByUsername(username, function(err, user) {
      if (err) throw err;
      if (!user) {
        return done(null, false, { message: 'Unknown User' });
      }
      User.comparePassword(password, user.password, function(err, isMatch){
        if(err) throw err;
        if(isMatch) {
          return done(null, user);
        } else {
          return done(null, false, {message: 'Invalid password'});
        }
      });
    });
}));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.getUserById(id, function(err, user) {
    done(err, user);
  });
});

router.post('/login',
  passport.authenticate('local', {successRedirect: '/', failureRedirect: '/users/login', failureFlash: true }),
  function(req, res) {
    res.redirect('/');
  });

router.get('/logout', function(req, res){
  req.logout();

  req.flash('success_msg', 'You are logged out');
  res.redirect('/users/login');
});

module.exports = router;
&#13;
&#13;
&#13;

&#13;
&#13;
//indexjs - file
var express = require('express');
var router = express.Router();

// Home Page
router.get('/', ensureAuthenticated, function(req, res){
  res.render('index');
});

function ensureAuthenticated(req, res,next){
    if(req.isAuthenticated()){
        return next();
    } else {
        //req.flash('error_msg', 'You are not logged in');
        res.redirect('/users/login');
    }
}

module.exports = router;
&#13;
&#13;
&#13;

代码

有人可以告诉我我做错了什么。

1 个答案:

答案 0 :(得分:0)

好像我能够纠正错误。我必须将我的data-id元素从我的div标签移动到我的锚标签:请参阅下面的代码:

<section class="jumbotron">
      <div class="container">
        <h1 class="jumbotron-heading text-center">User Page</h1>
        <h1 class="text-center">{{users.name}}</h1>
      </div>
      <div class="button">
        <button class="btn btn-danger delete-user"/*it was here first*/><a href="#" /*now it is here*/data-id={{users._id}}>Delete</a></button>
      </div>
</secion>