mongodb findOne() 不返回值 nodejs [英] Mongodb findOne () not return value nodejs

查看:68
本文介绍了mongodb findOne() 不返回值 nodejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我尝试在用户订阅我的 api 后进行一些电子邮件验证,但是当我执行 user.FindOne(token) 时,找到了用户,但我无法在数据库中获取用户的值返回我是一个大屁股阵列,我看不到有什么价值可以选择.我的代码:

Hi Guys i try to do some email verification after a user suscrib to my api but when i do user.FindOne(token), the user is find but i not able to get the value of the user in the database the return me a big ass array and i don't see wich value to choose. my code:

验证函数:

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) 我得到了未定义但如果我做 console.log(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:

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 返回一个 promise,您需要等待它解析读取值.

findOne returns a promise, you need to wait for it resolve to read the values.

把你的函数改成这样:

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

这篇关于mongodb findOne() 不返回值 nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆