如何从Mongodb获取数据

时间:2019-05-11 09:09:08

标签: node.js mongodb mongoose

我有以下代码段:

const slackProfiles = await Promise.all(

checkinsDetails.map(async ({ employeeEmail }) => {
    const employeeData = Employee.findOne({
      workEmail: employeeEmail,
    });

    console.log('employee ', employeeData);

    const slackId = employeeData ? employeeData.slackId : '';

当我在控制台中记录员工数据时,我会得到以下数据:

employee  Query {
   _mongooseOptions: {},
   _transforms: [],
   _hooks: Kareem { _pres: Map {}, _posts: Map {} },
   _executionCount: 0,
   mongooseCollection:
   NativeCollection {
      collection: null,
 opts:
  { bufferCommands: true,
    capped: false,
    '$wasForceClosed': undefined },
 name: 'employees',
 collectionName: 'employees',
 conn:
  NativeConnection {
    base: [Mongoose],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    options: null,
    otherDbs: [],
    relatedDbs: {},
    states: [Object],
    _readyState: 0,
    _closeCalled: false,
    _hasOpened: false,
    '$internalEmitter': [EventEmitter],
    _listening: false },
 queue: [],
 buffer: true,
 emitter:
  EventEmitter {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: undefined } },
 model:
{ [Function: model]
 hooks: Kareem { _pres: [Map], _posts: [Map] },
 base:
  Mongoose {
    connections: [Array],
    models: [Object],
    modelSchemas: [Object],
    options: [Object],
    _pluralize: [Function: pluralize],
    Schema: [Function],
    model: [Function],
    plugins: [Array] },
 modelName: 'Employee',
 ...

当我在await之前附加EMployee.findOne({})时,控制台中没有任何记录。我也尝试过

Employee.findOne({
      workEmail: employeeEmail,
    },(err,data)=>console.log("data",data);

但不输出任何内容。

2 个答案:

答案 0 :(得分:0)

console.log输出的是查询而不是结果。另外,从Node.js在MongoDB上触发查询的回调格式也不需要等待/异步。

假设Employee是一个收集对象,那么以下操作应该有效。在这种情况下,只需避免使用异步/等待,因为回调函数会处理它。

Employee.findOne({
      workEmail: employeeEmail,
    },(err,data)=>console.log("data",data);

答案 1 :(得分:0)

您应该尝试一下,我认为这对您有用。

Employee.findOne({workEmail: employeeEmail}).then(err, result) {console.log(result)};
相关问题