Mongodb findOne() 不是return 值nodejs

Mongodb findOne () not return value nodejs

我尝试在用户订阅我的 API 后进行一些电子邮件验证,但是当我这样做时 user.FindOne(token),找到了用户,但我无法获得用户的值数据库。 return 是一个大数组,我不知道该选择哪个值。我的代码:

验证函数:

const User = require('../models/User');
const Token = require('../models/Token');

module.exports = function (req, res, next) {
  const headToken = req.header('token');
  const token = Token.findOne({ token: headToken })
  if (!token) {
    return res.status(400).send('We were unable to find a valid token. Your token my have expired.')
  } else {
      console.log(token);
  }
  try {
    const user = User.findOne({ _id: token._userId})
    if (!user) return res.status(400).send('We were unable to find a user for this token.');
    if (user.isVerified) console.log('déja vérifié');;

    // Verify and save the user
    user.isVerified = true;
    user.save(function (err) {
      if (err) { return res.status(500).send({ msg: err.message }); }
      res.status(200).send("The account has been verified. Please log in.");
    });
    next();
  } catch (err) {
    res.status(400).send('Invalid Token');
  }
}

如果我做 console.log(token._userId) 或 console.log(token._id) 我得到 undefined 但如果我做 console.log(token) 我得到这个:

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map {}, _posts: Map {} },
  _executionCount: 0,
  mongooseCollection: NativeCollection {
    collection: Collection { s: [Object] },
    Promise: [Function: Promise],
    _closed: false,
    opts: {
      bufferCommands: true,
      capped: false,
      autoCreate: undefined,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'tokens',
    collectionName: 'tokens',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: [Object],
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: false,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _listening: false,
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      name: 'test',
      host: 'cluster0-shard-00-01-1lzx5.mongodb.net',
      port: xxxxx,
      user: 'xxxx',
      pass: 'xxxx',
      db: [Db]
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { Token },
  schema: Schema {
    obj: { _userId: [Object], token: [Object], createdAt: [Object] },
    paths: {
      _userId: [ObjectId],
      token: [SchemaString],
      createdAt: [SchemaDate],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      _userId: [Object],
      token: [Object],
      createdAt: [Object],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 2,
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typePojoToMixed: true,
      typeKey: 'type',
      id: true,
      noVirtualId: false,
      _id: true,
      noId: false,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      autoIndex: null,
      minimize: true,
      discriminatorKey: '__t',
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true
  },
  op: 'findOne',
  options: {},
  _conditions: { token: '05bfd1ff19ef015934e04d2a8f21d37d' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: NativeCollection {
      collection: [Collection],
      Promise: [Function: Promise],
      _closed: false,
      opts: [Object],
      name: 'tokens',
      collectionName: 'tokens',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'tokens'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

findOne returns一个promise,需要等待它解析读取值。

将您的函数更改为:

module.exports = async function (req, res, next) {
  const headToken = req.header('token');
  const token = await Token.findOne({ token: headToken })
  ... 
}