简体   繁体   中英

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.

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();

restaurantIds is a nested object, you must populate it:

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

getLocation = async(req, res) => {
   await Location.findOne(
    { name: req.query.locationName },   
    { restaurantIds: 1 })
    .populate('restaurantIds').then(location => {
        console.log(location);
        console.log(location._id);   
        console.log(location.restaurantIds);
        return location;
        })
        .catch(err => {
            throw err;
        })
  );
}

module.exports = { getLocation };

It's look like your restaurantIds is an array, so when you print it, you must use as array. Start by change:

console.log(location.restaurantIds);

to:

console.log(location.restaurantIds[0]);

In this example, you will be printing the first object in the array, and use it in your code as array, it will be OK.

Edit: After added the restaurantIds , and now we know it's array of ObjectID, and this kind of array cannot be printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM