0
votes

Consider my below code:

userSessionDetail.save((err, data) => {
    if (data) {
        console.log('User Session has been successfully created!');
        returnUserData = {
            username: user.username,
            sessionid: LoginUserModel.findOne({
                    email: req.body._usercredentials.email
                })
                .sort({
                    loginDateTime: 'desc'
                })
                .then((res) => {
                    // console.log(res._id) Successfully get value from promise
                    return res._id
                })
                .catch((err) => {
                    console.log(err);
                })
        }
        console.log(returnUserData.sessionid); //empty
    } else {
        console.log('While creating User Session, something went wrong.');
    }
})

What I'm trying is to get the value from my promise and put in my property value of sessionid. Above code doesn't give me the value from my promise. It shows me below results:

User Session has been successfully created! Promise { emitter:
EventEmitter { domain: null, _events: { reject: [Function] }, _eventsCount: 1, _maxListeners: undefined }, emitted: {}, ended: true }

Could you clarify how to pass the resulting 'res._id' to the value of property sessionid, and not the promise itself?

1
Ahmer, most likely you are not getting a value for sessionid because you are assigning a promise to that key, which is being returned from LoginUserModel.findOne(). You will probably want to call save() after the lookup promise for findeOne() resolves successfully (I am assuming this method returns a promise), but it is hard to tell without a little more context about what the req and res objects do.manbearshark

1 Answers

1
votes

mongoose's findone method returns a promise, and where the Promise.then() callback is executed when mongodb (eventually) returns the data:

userSessionDetail.save((err, data) => {
    if (data) {
        console.log('User Session has been successfully created!');
        LoginUserModel.findOne({
                            email: req.body._usercredentials.email
                        })
                        .sort({
                            loginDateTime: 'desc'
                        })
                        .then((res) => {
                            // console.log(res._id) Successfully get value from promise
                            returnUserData = {
                                username: user.username,
                                sessionid: res._id
                            }
                            console.log(returnUserData.sessionid); //empty
                        })
                        .catch((err) => {
                            console.log(err);
                        })
    } else {
        console.log('While creating User Session, something went wrong.');
    }
})