Ar2zee
Ar2zee

Reputation: 420

What is `_doc` inside mongoose (console.log show the same results with it and without)

I would like to have an answer what exactly ._doc mean in mongoose or mongodb. and why destructuring/... show an error in console.log but works fine in return statement.

Next 2 lines return the same objects so why it's there and what ._doc is doing console.log(event); // return the same objects console.log(event._doc); // return the same objects

`events: () => {
   return Event.find()
     .then(events => {
       return events.map(event => {
         console.log(event); // return the same objects
         console.log(event._doc); // return the same objects
         console.log(...event); /* Graphql say "Found non-callable @@iterator" but later, on return I'm using destructuring without any errors why ? */
           return {
              ...event._doc, 
               _id: event._doc._id.toString(), 
               date: new Date(event._doc.date).toISOString(),
               creator: user.bind(this, event._doc.creator)
                };
            })
        })`

It's how console.log(event); or console.log(event._doc); looks like

`{ _id: 5c1c6d928debd345a54de4ce,
  title: ' Test',
  description: 'Test',
  price: 26.99,
  date: 2018-12-21T04:35:30.672Z,
  creator: 5c1c699bc1f1423c0047d2f1,
  __v: 0 }
{ _id: 5c1d8cde6efd7f02832aa2fa,
  title: 'Test 2',
  description: 'another description',
  price: 23.22,
  date: 2018-12-22T01:01:18.735Z,
  creator: 5c1c699bc1f1423c0047d2f1,
  __v: 0 }
{ _id: 5c1d8d6f6f51b802fc32ab22,
  title: 'Test 3',
  description: 'another description 3',
  price: 123.22,
  date: 2018-12-22T01:03:43.543Z,
  creator: 5c1c699bc1f1423c0047d2f1,
  __v: 0 }`

So it's even not an array why I need a ... in return ? I'm following this code in tutorial but doesn't understand these 2 things so I'll highly appreciate any useful answer. I'm using: Mongo, MongoDb and GraphQl Thank you.

Upvotes: 2

Views: 1830

Answers (1)

BenSower
BenSower

Reputation: 1612

The _doc field lets you access the "raw" document directly, which was delivered through the mongodb driver, bypassing mongoose. This is also why you might get confusing results using console.log.

If you just log an mongoose element, the output can look very similar to the output of _doc, since mongoose has a toString() method that will output only the actual datapoints and not all the helperfunctions like (.save(),.update()...).

Check https://github.com/Automattic/mongoose#driver-access for more info

Upvotes: 3

Related Questions