Users getting overwritten but only sometimes in Node.js/Mongoose/Passport/Connect-Mongo app

收藏待读

Users getting overwritten but only sometimes in Node.js/Mongoose/Passport/Connect-Mongo app

I’m using Heroku/Mongolab (and I’ve tried it with MongoHQ), and the title shows my setup. Here’s my package.json:

"name": "metatf-web",
"version" : "0.0.3",
"dependencies": {
    "express": "*",
    "ejs": ">=0.4.2",
    "passport": "*",
    "passport-steam": "*",
    "validator": "*",
    "mongoose" : "*",
    "connect-mongo" : "latest",
    "mongodb" : "latest"
}

Basically when I create a new user, my database is overwriting a user in the database, but only sometimes. Here’s my User’s schema:

/**
 * Module dependencies
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
 * User Schema
 */
module.exports = function() {
  var Users = new Schema({
    steamid : { type: String }
    , regdate : { type: Date, default: Date.now }
    , avatar  : { type: String, default: "none" }
    , isadmin : { type: String, default: "no" }
  });
  mongoose.model("Users", Users);
};

Here’s the function I use to determine if a user is in the database, and one if not:

var checkIfUserAddToDbIfNot = function(req, res, next) {
  var steamID = req.user;
  require('./controllers/user_controller').get(steamID, function(err, doc) {
    console.log(doc);
    if (!doc) { // User not found
      require('./controllers/user_controller').create(steamID);
      console.log('User added');
    }
  });
  return next();
};

And my user_controller (CRUD):

/**
 * Module dependencies.
 */
 var mongoose = require('mongoose')
   , Users = mongoose.model("Users")
   , user = new Users();

// Create
exports.create = function (steamID) {
  if (steamID == 76561197991291041) { // Add me as an admin for when database resets.
    user.isadmin = 'yes';
  } else {
    user.isadmin = 'no';
  }
  user.steamid = steamID;
  user.save(function (err, callback) {
    if (err) throw err;
    console.log('User ' + user.steamid + ' added');
    console.log('Admin: ' + user.isadmin);
  });
};

// Read
exports.get = function (steamID, fn) {
  Users.findOne({ steamid: steamID }, function (err, doc) {
    if (err) return err;
    if (doc) {
      fn(null, doc);
    } else {
      fn(null, null); // User not found
    }
  });
};

Here is where the check user function is being called:

app.get('/auth/steam/return',
  passport.authenticate('steam', { failureRedirect: '/' }), checkIfUserAddToDbIfNot, function (req, res) {
    res.redirect('/');
  });

And finally here is my connect-mongo stuff:

app.use(express.session({
  secret: 'dont be walmarting',
  store: new MongoStore(sess_conf.db),
  cookie: {
    maxAge: new Date(Date.now() + 1209600000), // DO NOT CHANGE
    expires: new Date(Date.now() + 1209600000) // DO NOT CHANGE
  },
  maxAge : new Date(Date.now() + 1209600000), // DO NOT CHANGE
  expires: new Date(Date.now() + 1209600000) // DO NOT CHANGE
}));

Any help here would be appreciated, I can’t for the life of me figure out why users are being overwritten. I’ve tried clearing the cookies before adding a new user in the site because I thought it was the Connect-Mongo sessions, but that didn’t work. Thanks to anyone that can help me with this.

Edit: I’m initializing Passport sessions just under this:

// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
// END APP CONFIG (annotated)

Problem courtesy of: Tony Hill

Solution

I think this is your problem:

var mongoose = require('mongoose')
   , Users = mongoose.model("Users")
   , user = new Users(); // <-- this creates a module variable `user`, but only once                             
                         //     (the first time the file is require()'d)

// Create
exports.create = function (steamID) {

  // ...which is being re-used every time this function is called.
  // Instead, you need to create the new user here:
  var user = new Users;

  if (steamID == 76561197991291041) { // Add me as an admin for when database resets.
    user.isadmin = 'yes';
  } else {
    user.isadmin = 'no';
  }
  user.steamid = steamID;
  user.save(function (err, callback) {
    if (err) throw err;
    console.log('User ' + user.steamid + ' added');
    console.log('Admin: ' + user.isadmin);
  });
};

Solution courtesy of: robertklep

原文 : Node.js Recipes

相關閱讀

免责声明:本文内容来源于Node.js Recipes,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。