MongoDB findOne() Returning Weird Object - Can Someone Interpret It?

I’ve been stuck on my URL Shortener project.

I’m trying to save the URLs. A document is created when user posts the url.

I console.log the document, and it looks fine. It follows the schema I created, with an extra _id added to it.

I save the url document to the database, then I use findOne() to see if it’s there. Here’s what I get when I try to console.log the result:

Query {

  _mongooseOptions: {},

  mongooseCollection:

   NativeCollection {

     collection: null,

     opts:

      { bufferCommands: true,

        capped: false,

        '$wasForceClosed': undefined },

     name: 'urls',

     collectionName: 'urls',

     conn:

      NativeConnection {

        base: [Mongoose],

        collections: [Object],

        models: [Object],

        config: [Object],

        replica: false,

        hosts: null,

        host: null,

        port: null,

        user: null,

        pass: null,

        name: null,

        options: null,

        otherDbs: [],

        states: [Object],

        _readyState: 0,

        _closeCalled: false,

        _hasOpened: false,

        _listening: false },

     queue: [ [Array] ],

     buffer: true,

     emitter:

      EventEmitter {

        _events: [Object: null prototype] {},

        _eventsCount: 0,

        _maxListeners: undefined } },

  model:

   { [Function: model]

     hooks: Kareem { _pres: {}, _posts: {} },

     base:

      Mongoose {

        connections: [Array],

        models: [Object],

        modelSchemas: [Object],

        options: [Object],

        plugins: [Array] },

     modelName: 'Url',

     model: [Function: model],

     db:

      NativeConnection {

        base: [Mongoose],

        collections: [Object],

        models: [Object],

        config: [Object],

        replica: false,

        hosts: null,

        host: null,

        port: null,

        user: null,

        pass: null,

        name: null,

        options: null,

        otherDbs: [],

        states: [Object],

        _readyState: 0,

        _closeCalled: false,

        _hasOpened: false,

        _listening: false },

     discriminators: undefined,

     '$appliedMethods': true,

     '$appliedHooks': true,

     _events:

      [Object: null prototype] { init: [Function], save: [Function] },

     _eventsCount: 2,

     schema:

      Schema {

        obj: [Object],

        paths: [Object],

        aliases: {},

        subpaths: {},

        virtuals: [Object],

        singleNestedPaths: {},

        nested: {},

        inherits: {},

        callQueue: [Array],

        _indexes: [],

        methods: {},

        statics: {},

        tree: [Object],

        query: {},

        childSchemas: [],

        plugins: [Array],

        s: [Object],

        _userProvidedOptions: undefined,

        options: [Object],

        '$globalPluginsApplied': true,

        _requiredpaths: [] },

     collection:

      NativeCollection {

        collection: null,

        opts: [Object],

        name: 'urls',

        collectionName: 'urls',

        conn: [NativeConnection],

        queue: [Array],

        buffer: true,

        emitter: [EventEmitter] },

     Query: { [Function] base: [Query] },

     '$__insertMany': [Function],

     insertMany: [Function],

     '$init':

      Promise { emitter: [EventEmitter], emitted: [Object], ended: false } },

  schema:

   Schema {

     obj: { url: [Object] },

     paths:

      { url: [SchemaString], _id: [ObjectId], __v: [SchemaNumber] },

     aliases: {},

     subpaths: {},

     virtuals: { id: [VirtualType] },

     singleNestedPaths: {},

     nested: {},

     inherits: {},

     callQueue: [ [Array], [Array], [Array], [Array], [Array], [Array] ],

     _indexes: [],

     methods: {},

     statics: {},

     tree:

      { url: [Object],

        _id: [Object],

        __v: [Function: Number],

        id: [VirtualType] },

     query: {},

     childSchemas: [],

     plugins: [ [Object], [Object], [Object], [Object] ],

     s: { hooks: [Kareem], kareemHooks: [Object] },

     _userProvidedOptions: undefined,

     options:

      { retainKeyOrder: false,

        typeKey: 'type',

        id: true,

        noVirtualId: false,

        _id: true,

        noId: false,

        validateBeforeSave: true,

        read: null,

        shardKey: null,

        autoIndex: null,

        minimize: true,

        discriminatorKey: '__t',

        versionKey: '__v',

        capped: false,

        bufferCommands: true,

        strict: true,

        pluralization: true },

     '$globalPluginsApplied': true,

     _requiredpaths: [] },

  op: 'findOne',

  options: { retainKeyOrder: false },

  _conditions: { url: 'https://www.freecodecamp.org' },

  _fields: undefined,

  _update: undefined,

  _path: undefined,

  _distinct: undefined,

  _collection:

   NodeCollection {

     collection:

      NativeCollection {

        collection: null,

        opts: [Object],

        name: 'urls',

        collectionName: 'urls',

        conn: [NativeConnection],

        queue: [Array],

        buffer: true,

        emitter: [EventEmitter] },

     collectionName: 'urls' },

  _traceFunction: undefined,

  _count: [Function],

  _execUpdate: [Function],

  _find: [Function],

  _findOne: [Function],

  _findOneAndRemove: [Function],

  _findOneAndUpdate: [Function],

  _replaceOne: [Function],

  _updateMany: [Function],

  _updateOne: [Function],

  _error: null }

What the heck is all that? All I want is to find the url I saved and to look up its id. How do I test to see if something is successfully saved into the database? The challenges only tell us to ‘find’ or ‘find and update’ documents. How do we actually access the information returned by the database, given that the above is what we get back?

I don’t know what that all means, but have you actually looked in your database to see what is being saved?

You mean log onto mongo? I’ve never done that. Didn’t know I could do that.

Huh. I see “People” in collections, from the challenges we did. Nothing else. That means it didn’t work. I don’t know why. I did everything the same.

Maybe a link to your code would help.

Here it is:

I trust that the env variables would remain ‘secret’ (like it says when I copied the link)

Yes, the .env files remain secret. The link doesn’t work though. For some reason I’ve had to do
<a href="mylink"> here</a> to get the glitch link to work.

Thanks for looking into this

…I’ve tried a bunch of links. They’re not working for me either. As long as you got it to work…

No what I’m saying is the link still doesn’t work. I know freecodecamp would like you to do the link like you did, but that doesn’t work for glitch. You need to use the html a element like you would do in html:
<a href="copyAndPastYourLinkHere"> here</a>

Here’s the link

Ahh, there. Now the link works. Smart!

Callbacks might help you here. One to check if you are connected to the database like

mongoose.connect(process.env.MONGO_URI, function(err) {
  if (err) { 
    console.log(err);
    } else {
    console.log("connected to db!")
  }
});

also instead of

url.save();
  console.log(Url.findOne({url: req.body.url}));

try

url.save( function (err, data) {
  if (err) {
        console.log(err);
        } else {
          console.log(data);
      }
1 Like

@eoja I tried the url.save(call back function) doing exactly what you did there, but it doesn’t enter the function at all. Nothing gets logged in the console. I’ll try adding call back to the mongoose.connect to see if it’s connecting at all.

I tried the call back with the mongoose.connect. Nothing gets logged with console.log. Neither the error message nor “Connected to db!”. Any ideas why?

Another thing you can try is to update your mongdb and mongoose dependencies.

1 Like

The versions were old, so I used the newer version. Still not getting any console.log messages indicating error or not

EDIT: Whoops. Nevermind. I see the console.log message “Connected to DB!”

1 Like

YESSS!!! Finally! I see the documents getting saved into MongoDB. Oh man, this took me the whole day. I’m still far from finished.

Thank you so much @eoja. I was getting so frustrated wondering what was wrong, reading up one the mongoDB documentation and finnding no answers. Turns out I was using old dependencies. That should’ve been the first thing I checked.

Thanks again!

:+1: :grinning:

1 Like

@LiChoi

About your original question (in the thread title), hopefully this will help you out a little…

Assume you have a collection in your database called ‘issues’ and you are able to successfully save an individual ‘issue’ (the model is ‘Issue’). If you try to find that issue by, say, its id, you might write the following method to get it.

app.get("/issues/:id", (req, res) => {
    console.log(req.params.id)
    const myIssue = Issue.findById(req.params.id)
    console.log(myIssue)  
})

And, if you do, you’ll get that ‘weird object’ logged to the console. That is a Mongoose ‘Query’ object, which you can use to build queries. You can chain the exec() method to it to complete the database search. From the MongoDB and Mongoose - Chain Search Query Helpers to Narrow Search Results … challenge at fCC:

If you don’t pass the callback as the last argument to Model.find() (or to the other search methods), the query is not executed. You can store the query in a variable for later use. This kind of object enables you to build up a query using chaining syntax. The actual db search is executed when you finally chain the method .exec(). Pass your callback to this last method. There are many query helpers, here we’ll use the most ‘famous’ ones.

Now, things are made much easier if you use ‘async/await’.

app.get("/issues/:id", async (req, res) => {
    console.log(req.params.id)
    const myIssue = await Issue.findById(req.params.id)
    console.log(myIssue)  
})

Do this and you’ll see that your document from the collection ‘issues’ is saved to myIssue nicely.

{ _id: 5d351333bnvvvcc6c4212,
  issueName: 'office too cold',
  userName: 'neverHappy',
  message: 'Please stop making the office so cold!',
  __v: 0 }

Of course, this is assuming you’re able to save the document to the collection correctly.

2 Likes

Thank you @willjw3 for teaching me how to retrieve info on our documents!

So in summary, find() will give me the ‘weird object’ if I don’t pass in a call back (meaning the function that takes in error or the returned data). That weird object is an incomplete search query that just hangs there until I pass in the callback? I see. I was wondering what that last challenge meant.

So if I pass in a call back to find( ), I’ll get the document?

Alternatively, I could use the other method you mentioned with async and await.

Good to know. Thanks!

1 Like