猫鼬返回模型对象内的文档

时间:2019-05-19 09:40:56

标签: mongoose

无论何时我用控制台记录已创建的文档或查询它,即使使用.require(),返回的东西也太多了。看来文档已返回模型对象内部。

我将代码最小化了。

/* jshint  esversion: 8 */                                                                                   

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/freecodecamp-learning-mongoose')
  .then (()=> console.log('Connected to MongoDB...'))
  .catch(err => console.error('Could not connect to mongoDB', err));

const Schema1 = new mongoose.Schema({
  name: String,
});

const DocumentModel = mongoose.model('Document',Schema1);

async function createDocument(){
  const document = new DocumentModel({
    name: 'document name'
  });
  const result = await document.save();
  console.log(result);
}

createDocument();


async function getAllDocuments(){
  const documents = await DocumentModel.find().select({name:1});//.count();
console.log(documents);
}

// getAllDocuments();

这是我执行该命令所得到的...即使我使用.select()

查询
model {
  '$__': InternalCache {
    strictMode: true,
    selected: undefined,
    shardval: undefined,
    saveError: undefined,
    validationError: undefined,
    adhocPaths: undefined,
    removing: undefined,
    inserting: true,
    version: undefined,
    getters: {},
    _id: 5ce11d9cf5675b6482d0fa38,
    populate: undefined,
    populated: undefined,
    wasPopulated: false,
    scope: undefined,
    activePaths: StateMachine {
      paths: {},
      states: [Object],
      stateNames: [Array],
      map: [Function]
    },
    pathsToScopes: {},
    ownerDocument: undefined,
    fullPath: undefined,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: 0
    },
    '$options': true
  },
  isNew: false,
  errors: undefined,
  _doc: { _id: 5ce11d9cf5675b6482d0fa38, name: 'document name', __v: 0 }

查询本身可以正常工作,即使我查询.count(),我也会得到正确的金额(在这种情况下为1)。

1 个答案:

答案 0 :(得分:0)

猫鼬查询返回猫鼬文档类的实例。您需要使用lean以避免Document Class的实例。 在getAllDocuments函数中使用以下代码:

const documents = await DocumentModel.find().select({name:1}).lean()

参考:https://mongoosejs.com/docs/tutorials/lean.html#using-lean