Mongoose无法从Schema获得_id

时间:2017-09-17 09:37:00

标签: node.js mongodb express mongoose

我有一个看起来像这样的UserSchema:

export var UserSchema: Schema = new mongoose.Schema({
  createdAt: Date,
  email: {
    type: String,
    required: true,
    trim: true,
    unique: false,
  },
  firstName: {
    type: String,
    required: false,
    trim: true
  },
  lastName: {
    type: String,
    required: false,
    trim: true
  },
  password: {
    type: String,
    trim: true,
    minlength: 6
  },
  tokens: [{
    access: {
      type: String,
      required: true
    },
    token: {
      type: String,
      required: true
    }
  }]
});

我有一个实例方法,如:

   UserSchema.methods.printThis =  () => {
        var user = this;
        console.log("========>>> PRINTING USER NOW");
        console.log(user);
};

正在从

调用方法printThis
router.post('/signup', (req, res) => {
    var body = _.pick(req.body, ['email', 'password']);
    var user = new User(body);

    console.log("created user as: ", user);

    user.printThis();
});

以下是输出:

created user as:  { email: 'prsabodh.r@gmail.com',
  password: '123456',
  _id: 59be50683606a91647b7a738,
  tokens: [] }
========>>> PRINTING USER NOW
{}

您可以看到正确创建了用户。但是,当我在printThis上调用User方法时 - 我无法打印同一个用户,并打印出空{}。如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果调用函数显式设置上下文(这是Mongoose所做的),则不应使用箭头函数(=>):

UserSchema.methods.printThis = function() {
  var user = this;
  console.log("========>>> PRINTING USER NOW");
  console.log(user);
};

有关箭头功能及其this处理方式的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Arrow_functions

答案 1 :(得分:0)

要从实例方法获取_id值,可以使用应该有效的_conditions

UserSchema.methods.printThis = function(password) {
    var user = this;
    console.log(user._conditions['_id']);
};