Reputation: 43
whenever I console log a created document, or when I query it, even with .require() I just get too much stuff returned. It looks like the documents are returned inside the model object.
I have minized my code to the minimum.
/* 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();
this is what I get if I execute it... even if i query with .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 }
the queries themselves work fine, and even If I query for a .count() I would get the right amount (in this case 1).
Upvotes: 1
Views: 919
Reputation: 266
Mongoose queries return instance of the Mongoose Document Class. You need to use lean
in order to avoid the instance of the Document Class.
Use the following code inside your getAllDocuments
function:
const documents = await DocumentModel.find().select({name:1}).lean()
Reference: https://mongoosejs.com/docs/tutorials/lean.html#using-lean
Upvotes: 4