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

Time:03-25

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....

  • 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!

CodePudding user response:

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

  • Related