如何使用Mongoose 7.3.1打印数据库文档

huangapple go评论65阅读模式
英文:

How to print documents of a database using Mongoose 7.3.1

问题

你可以使用.lean()方法来将Mongoose查询结果转换为普通JavaScript对象,然后将其打印到控制台。尝试以下代码:

Fruit.find({}).lean().exec(function(err, fruits) {
  if (err) {
    console.error(err);
  } else {
    console.log(fruits);
  }
});

这将允许你将数据库中的文档作为普通对象输出到控制台,而不是Mongoose查询对象。

英文:

I am currently using Mongoose 7.3.1 and have inserted a few documents into the MongoDB database and I am unable to log the documents using console.log() by simply using the Fruit.find({}) and logging it to the console all it spits out is a huge data set of unwanted objects.

The unwanted output is this

Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
  mongooseCollection: Collection {
    collection: null,
    Promise: [Function: Promise],
    modelName: 'Fruit',
    _closed: false,
    opts: {
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: {},
      capped: false,
      Promise: undefined,
      '$wasForceClosed': undefined
    },
    name: 'fruits',
    collectionName: 'fruits',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: {},
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 2,
      _closeCalled: false,
      _hasOpened: false,
      plugins: [],
      id: 0,
      _queue: [Array],
      _listening: false,
      _connectionOptions: [Object],
      _connectionString: 'mongodb://localhost:27017/fruitsDB',
      client: [MongoClient],
      '$initialConnection': [Promise]
    },
    queue: [],
    buffer: true,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { Fruit },
  schema: Schema {
    obj: {
      name: [Function: String],
      rating: [Function: Number],
      review: [Function: String]
    },
    paths: {
      name: [SchemaString],
      rating: [SchemaNumber],
      review: [SchemaString],
      _id: [ObjectId],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: {},
    methodOptions: {},
    statics: {},
    tree: {
      name: [Function: String],
      rating: [Function: Number],
      review: [Function: String],
      _id: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    mapPaths: [],
    s: { hooks: [Kareem] },
    _userProvidedOptions: {},
    options: {
      typeKey: 'type',
      id: true,
      _id: true,
      validateModifiedOnly: false,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: false,
      strict: true,
      pluralization: true
    },
    '$globalPluginsApplied': true,
    _requiredpaths: []
  },
  op: 'find',
  options: {},
  _conditions: {},
  _fields: undefined,
  _updateDoc: undefined,
  _path: undefined,
  _distinctDoc: undefined,
  _collection: NodeCollection {
    collection: Collection {
      collection: null,
      Promise: [Function: Promise],
      modelName: 'Fruit',
      _closed: false,
      opts: [Object],
      name: 'fruits',
      collectionName: 'fruits',
      conn: [NativeConnection],
      queue: [],
      buffer: true,
      emitter: [EventEmitter]
    },
    collectionName: 'fruits'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

I even tried inspecting the objects for the documents from the database but was unable to find any.

Mongoose official documentation here mentions using the above code to find the documents but it's not showing the documents.

How can I log the documents to the terminal using Mongoose?

答案1

得分: 2

你遇到的问题是由于数据库调用的异步性质引起的。Mongoose 的 find 方法返回一个 Query 对象,它的行为类似于一个 Promise,你需要相应地处理它。你可以尝试使用 .then() 或 async/await 来处理它。类似于这样:

Fruit.find({}).then((docs) => {
    console.log(docs);
}).catch((err) => {
    console.error(err);
});
英文:

The issue you're encountering is due to the asynchronous nature of database calls. The find method of Mongoose returns a Query object which acts like a promise, which you need to handle accordingly. You can try handling it using .then() or async/await. Something similar to this:

Fruit.find({}).then((docs) => {
    console.log(docs);
}).catch((err) => {
    console.error(err);
});

huangapple
  • 本文由 发表于 2023年6月29日 19:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定