使用mongoose重新提交表单时出错

时间:2016-10-19 07:08:25

标签: node.js mongodb

我是NodeJs&&的新手。 mongoose developpment。

我构建了一个与用户交互的NodeJS应用程序,用于在创建新帐户时检查用户是否已存在。

所以在第一次提交信息时,它会按照我的预期返回(用户存在)。再次提交表单,它会返回错误mongoose error when submit again the form.

这是我的代码,我提前感谢您的帮助。

user.js的

var mongoose = require("../DB");

var User = {
  io: {},
  Model: function() {
    return mongoose.model('users', this.userSchema());
  },
  userSchema: function() {
    userSchema = mongoose.Schema({
      firstname: String,
      username: String,
      email: String,
      password: String
    });
    return userSchema;
  },
  checkAuthentication: function(user) {
    this.Model().findOne(user, function(err, oUser) {
      if (!oUser) {
        socket.emit("noMatchUser", user);
        return false;
      }

    });
  },
  checkUser: function(newUser) {

    this.Model().find({
      username: newUser.username
    }, function(err, users) {

      if (err) {
        console.log("erreur");
        return false;
      }
      if (users.length >= 1) {
        User.getSocket().emit("userExist", newUser);
        return false;
      }
      User.saveUser(newUser);
    });
  },
  saveUser: function(newUser) {
    console.log("user saved");
    var nUser = new User.Model();
    nUser.email = newUser.email;
    nUser.username = newUser.username;
    nUser.firstname = newUser.firstname;
    nUser.password = newUser.password;
    nUser.save(function(error) {
      if (error) {
        socket.emit("newUserFail");
        return false;
      }
    })
  },
  setSocket: function(socket) {
    this.socket = socket;

  },
  getSocket: function() {
    return this.socket;
  }
};
module.exports = User;
var express = require("express"),
  http = require("http"),
  mongoose = require("mongoose"),
  bodyParser = require("body-parser"),
  app = express(),
  server = app.listen(3000),
  io = require("socket.io").listen(server);

var router = express.Router();
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
var User = require("./lib/Models/User");
User.setSocket(io);
app.set("view engine", "ejs");

io.sockets.on("connection", function(socket) {
  socket.on("login", function(user) {
    User.checkAuthentication(user);
  });

  socket.on("checkuser", function(newAccount) {
    User.checkUser(newAccount);
    return false;
  });
});

app.use("/", router);
router.route('/')
  .get(function(request, response) {
    response.render("pages/index");
  });

router.route('/create-account')
  .get(function(request, response) {
    response.sendFile("account.html", {
      "root": __dirname
    });
  });

app.use(express.static('public'));  

0 个答案:

没有答案