Home > front end >  Why object key returns undefined even though value exists
Why object key returns undefined even though value exists

Time:11-01

I want to access key to an object but it returns undefined and I don't know why

This is my code

const docs = await this.walletModel.find({
      status: 'Venus'
    }).select('user meteorite').populate('user', 'name extra.profilePic extra.thumbnail').lean()

    // @ts-ignore
    const userIds = docs.map(user => Types.ObjectId(user?.user?._id))

    const boughtUsers = await this.subscriptionModel.find({ user: { $in: userIds } }).select('-_id user')

    const reduced = docs.reduce((acc, curr) => {
      // @ts-ignore
      if (boughtUsers.some(boughtUser => {
        // @ts-ignore
        console.log(boughtUser, curr?.user?._id) // logging here

        // @ts-ignore
        return boughtUser?.user === curr?.user?._id
      })) return [...acc, {...curr}]

      return [...acc, {...curr, gift: true}]
    }, [])

    return reduced

it returns

enter image description here

as you can see there are user keys but when I am trying to log it it returns undefined

code

const docs = await this.walletModel.find({
      status: 'Venus'
    }).select('user meteorite').populate('user', 'name extra.profilePic extra.thumbnail').lean()

    // @ts-ignore
    const userIds = docs.map(user => Types.ObjectId(user?.user?._id))

    const boughtUsers = await this.subscriptionModel.find({ user: { $in: userIds } }).select('-_id user')

    const reduced = docs.reduce((acc, curr) => {
      // @ts-ignore
      if (boughtUsers.some(boughtUser => {
        // @ts-ignore
        console.log(boughtUser?.user, curr?.user?._id) // logging here

        // @ts-ignore
        return boughtUser?.user === curr?.user?._id
      })) return [...acc, {...curr}]

      return [...acc, {...curr, gift: true}]
    }, [])

    return reduced

returns

enter image description here

CodePudding user response:

I have tried to logging with Object.entries() and it returned something like that

[
  [
    '$__',
    InternalCache {
      strictMode: false,
      selected: [Object],
      shardval: undefined,
      saveError: undefined,
      validationError: undefined,
      adhocPaths: undefined,
      removing: undefined,
      inserting: undefined,
      saving: undefined,
      version: undefined,
      getters: {},
      _id: undefined,
      populate: undefined,
      populated: undefined,
      wasPopulated: false,
      scope: undefined,
      activePaths: [StateMachine],
      pathsToScopes: {},
      cachedRequired: {},
      session: null,
      '$setCalled': Set(0) {},
      ownerDocument: undefined,
      fullPath: undefined,
      emitter: [EventEmitter],
      '$options': [Object]
    }
  ],
  [ 'isNew', false ],
  [ 'errors', undefined ],
  [ '$locals', {} ],
  [ '$op', null ],
  [ '_doc', { user: 6179847*******104c5715ee } ],
  [ '$init', true ]
]

I added lean option to boughtUsers query and fixed my problem

  • Related