I'm trying to get a property from MongoDB (mongoose) using the Model.findById()
method. When I console.log
the response, everything looks fine. But I cannot access it's properties.
//Fetch the conversations
var conversations = await ChatConversation.find({ members: req.token.mid }, 'members is_group').exec();
//Loop through the conversations to and modify each conversation
conversations = await Promise.all(conversations.map(async (conversation) => {
if(conversation.is_group === false){
// A conversation contains 2 members, get the user who is not logged in
var other_id = conversation.members[0] == req.token.mid ? conversation.members[1] : conversation.members[0];
//Fetch the other participant's details
var other_participant = await User.findById(other_id, 'name photo');
/* PROBLEM HERE */
console.log(other_participant)
//Assign the newly fetch values
conversation.name = other_participant.name;
conversation.picture = other_participant.picture;
}
return conversation;
}))
This is the code snippet. The log I get is
{ _id: 60b23d231d6fb73eb43eb5f5, name: 'Ajith Gopi', photo: '' }
But if I try to access the name property like other_participant.name
it gives undefined
I have tried to get the keys and values of other_participant
using Object.keys(other_participant)
and Object.values(other_participant)
, I get the following
Object.keys(other_participant)
:
[
'$__', 'isNew',
'errors', '$locals',
'$op', '_doc',
'$init'
]
Object.values(other_participant)
:
[
InternalCache {
strictMode: true,
selected: { name: 1, photo: 1 },
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: 60b23d231d6fb73eb43eb5f5,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: [Object],
states: [Object],
stateNames: [Array]
},
pathsToScopes: {},
cachedRequired: {},
session: undefined,
'$setCalled': Set(0) {},
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0,
[Symbol(kCapture)]: false
},
'$options': { skipId: true, isNew: false, willInit: true, defaults: true }
},
false,
undefined,
{},
null,
{ _id: 60b23d231d6fb73eb43eb5f5, name: 'Ajith Gopi', photo: '' },
true
]
Mongoose Schema:
const User = mongoose.model('User', new mongoose.Schema({
phone: Number,
name: String,
photo: String,
date_created: { type: Date, default: Date.now },
}), 'users');
I'm not sure, But I suspect it has something to do with the Promise.all()
...
NB: I have also tried replacing findById()
with findOne()
, And tried adding exec()
in the end too... Same results