简体   繁体   English

为什么 array.push() 在我的 Mongoose 模型中不起作用?

[英]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.我是 Node.js 的初学者,我在我的第一个脚本中苦苦挣扎。 My problem is that I want to push an object into an array that is defined by a Mongoose object.我的问题是我想将一个对象推送到一个由 Mongoose 对象定义的数组中。

Here is my object definition.这是我的对象定义。 You'll see three different attemps, (two commented) to push the object in the definition of the generateAuthToken method:您将看到三种不同的尝试(两个注释)在 generateAuthToken 方法的定义中推送对象:

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:在服务器中通过以下路由调用 generateAuthToken():

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.当我将该路由与有效数据一起使用时,会返回 400 错误。 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.我在终端中没有收到任何错误,但是通过替换 console.log() 调用,我可以缩小 this.tokens.push() 调用的错误范围。 Nothing of the method executes from there.没有任何方法从那里执行。

So, can someone help me chase down the mistake?那么,有人可以帮我追查错误吗?

Using node 10.9.0 and:使用节点 10.9.0 和:

"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!谢谢!

You are using short-hand json when pushing objects into your array.将对象推入数组时,您使用的是简写 json。 You however, have a typo on acces :但是,您在acces上有一个错字:

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

It should be: this.tokens.push({access, token});应该是: this.tokens.push({access, token}); (note: acces -> access , with two s's, not one) (注意: acces -> access ,有两个 s,而不是一个)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM