eichan
eichan

Reputation: 95

Why isn't array.push() working in my Mongoose model?

I'm a beginner with Node.js and I'm struggling here with one of my first scripts. My problem is that I want to push an object into an array that is defined by a Mongoose object.

Here is my object definition. You'll see three different attemps, (two commented) to push the object in the definition of the generateAuthToken method:

const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');

let UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    minlength: 1,
    trim: true,
    unique: true,
    validate: {
      validator: validator.isEmail,
      message: '{VALUE} is not a valid email'
    }
  },
  password: {
    type: String,
    required: true,
    minlength: 6
  },
  tokens: [{
    access: {
      type: String,
      required: true
    },
    token: {
      type: String,
      required: true
    }
  }]
});

UserSchema.method('generateAuthToken', function () {    
  // let user = this;
  let access = 'auth';
  let token = jwt.sign({ _id: this._id.toHexString(), access }, 'secret').toString();

  console.log(token);
  console.log(jwt.verify(token, 'secret'));
  console.log(this.tokens);

  // user.tokens[] = {access, token};
  this.tokens.push({ acces, token });
  // user.tokens = user.tokens.concat([{access, token}]);

  return this.save().then(() => {
    return token;
  });

});

let User = mongoose.model('User', UserSchema);

module.exports = { User };

The generateAuthToken() is called in the server with the following route:

app.post("/users", (req, res) => {
  let user = new User(_.pick(req.body, ["email", "password"]));

  user
    .save()
    .then(doc => {
      return user.generateAuthToken();
    })
    .then(token => {
      res.header("x-auth", token).send(user);
    })
    .catch(e => {
      res.status(400).send(e);
    });
});

When I use that route with valid data, I get returned a 400 error. The user object is written in the database, but its tokens array is empty. I don't get any error in the terminal but by displacing console.log() calls I could narrow down the bug the this.tokens.push() call. Nothing of the method executes from there.

So, can someone help me chase down the mistake?

Using node 10.9.0 and:

"body-parser": "^1.18.3",
"express": "^4.16.3",
"jsonwebtoken": "^8.3.0",
"lodash": "^4.17.10",
"mongodb": "^3.1.4",
"mongoose": "^5.2.10",
"validator": "^10.7.1"

Thanks!

Upvotes: 0

Views: 275

Answers (1)

dvsoukup
dvsoukup

Reputation: 1596

You are using short-hand json when pushing objects into your array. You however, have a typo on acces:

this.tokens.push({acces, token});

It should be: this.tokens.push({access, token}); (note: acces -> access, with two s's, not one)

Upvotes: 2

Related Questions