简体   繁体   English

Mongodb findOne() 没有返回值 nodejs

[英]Mongodb findOne () not return value nodejs

I try to do some email verification after a user subscribes to my API, but when I do user.FindOne(token) , the user is found but I not able to get the value of the user in the database.在用户订阅我的 API 后,我尝试进行一些 email 验证,但是当我执行user.FindOne(token)时,找到了用户,但我无法在数据库中获取用户的值。 The return is a big ass array and I don't see which value to choose.返回是一个大数组,我看不出要选择哪个值。 my code:我的代码:

ValidationFunction:验证功能:

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');
  }
}

if I do console.log(token._userId) or console.log(token._id) I got undefined but if I do console.log(token) I got this:如果我执行 console.log(token._userId) 或 console.log(token._id) 我得到未定义但如果我执行 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 a promise , you need to wait for it resolve to read the values. findOne返回一个promise ,您需要等待它解析读取值。

change your function into this:将您的 function 更改为:

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

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

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