Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't access object property after it being retrieved from mongoose

I’m trying to access a property inside of an object that was retrieved by mongoose

 const eventToDelete=await EventModel.find({"creator":_id});
         const id_chat=eventToDelete.chat;
         console.log(eventToDelete);  
         console.log(id_chat);  

the output:

[
  {
    _id: new ObjectId("623c71630e1ab7b02941fe51"),
    title: 'House Party',
    description: "This Saturday 10pm",
    type: 'Party',
    lat: -37.50328,
    lng: -52.28816,
    date: 2022-03-24T13:25:27.319Z,
    creator: '623c6de2aeafdc7a0f9ac42d',
    chat: '623c71630e1ab7b02941fe52',
    __v: 0
  }
]
undefined

I read that apparently the console.log is not showing me the real deal because It changes the structure of the response or something like that, but I don’t understand how to achieve what I need( accessing that value) that’s why I’m asking for help doing so….

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • I tried using a toObject() function as one of the answer to similar problems recommended

but I received the following error

eventToDelete.toObject is not a function
  • I do have chat in the event schema ( that was the most recommended solution I found)
import mongoose from 'mongoose';

const eventSchema= mongoose.Schema(
    {
        title: {type:String, required:true},
        description:  {type:String, default:''},
        type:  {type:String, default:''},
        img:{type:String, default:''},
        lat:{type:Number, default:0.0},
        lng:{type:Number, default:0.0},
        date:{type:Date, default:new Date()},
        creator: {type:String, required:true},
        chat: {type:String, default:''},
     
    }
)

const EventModel= mongoose.model("EventModel",eventSchema);
export default EventModel;

What am I missing ?
Please help!

>Solution :

You are not able to access the property because .find() returns an array.

You can see that the object you get from console.log(eventToDelete) have [] around it.

You will have to do something like this

const id_chat = eventToDelete[0].chat;

You can use .findOne() if you are expecting only one result from your query

Check here how to use .findOne()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading