MongoDB collection.findOne() returns undefined value

const Location = require("../models/locations");

getLocation = async(req, res) => {
   await Location.findOne(
    { name: req.query.locationName },     // req.query.locationName is "Gurgaon"
    { restaurantIds: 1 },
    (err, location) => {
      if (err) throw err;
      else {
        console.log(location);
        /*
               {
                   _id: 6004f9cff6ae9921f89f0f81,
                   restaurantIds: [ 6004fb53f6ae9921f89f0f83, 600792321b229bae25a66497 ]
               }
        */
        console.log(location._id);    // 6004f9cff6ae9921f89f0f81
        console.log(location.restaurantIds);     // undefined
        return location;
      }
    }
  );
}

module.exports = { getLocation };

Screenshot of the output

This is how the locations collection looks like.

{
  "_id" : ObjectId("6004f9cff6ae9921f89f0f81"),
  "name" : "Gurgaon",
  "restaurantIds" : [
          ObjectId("6004fb53f6ae9921f89f0f83"),
          ObjectId("600792321b229bae25a66497")
  ]
}

Here is the locations schema.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const Locations = new Schema({}, { strict: false });

module.exports = mongoose.model("locations", Locations);

I don’t know the reason why location.restaurantIds is returning me undefined. Please help me with this. I am new to mongodb.

Answer

There will be some reasons might be you have not specified this field in your mongoose schema, try adding field in your schema and you are able to access this field in your query.


Second option if you don’t want to specify that field in schema then try lean(),

By default, Mongoose queries return an instance of the Mongoose Document class. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.

await Location.findOne(.. your query).lean();

Leave a Reply

Your email address will not be published. Required fields are marked *