Mongodb findOne()不会返回值nodejs

编程入门 行业动态 更新时间:2024-10-10 10:30:30

Mongodb findOne()不会<a href=https://www.elefans.com/category/jswz/34/1769942.html style=返回值nodejs"/>

Mongodb findOne()不会返回值nodejs

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

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

如果我执行console.log(token._userId)或console.log(token._id),我不确定,但是如果我执行console.log(token.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',
      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,您需要等待它解析为读取值。

将您的功能更改为此:

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

更多推荐

Mongodb findOne()不会返回值nodejs

本文发布于:2024-05-07 15:52:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   Mongodb   findOne   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!