Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add key/value pair to returned mongoose object

I have code that retrieves a Mongoose object and then uses the stripeCustomerId (stored in the document) to retrieve the Stripe customer object (via nodejs stripe). I then want to attach the stripe customer object to my Mongoose object.

exports.getPlatformByCId = (cId) => {
    return new Promise((resolve, reject) => {
        Platform.find({ clientId: cId }).then(response => {
            let user = response[0];
            stripe.customers.retrieve(user.stripeCustomerId, (err, stripeCust) => {                
                if(err) {
                    user["stripeCustomer"] = null;
                } else {
                    user["stripeCustomer"] = stripeCust;
                }
                resolve(user);
            })
        }).catch(err => {
            if(err) {
                if(err.error !== 'not_found') {
                    resolve(err);
                } else {
                    reject(err);
                }
            }
        })
    })
}

I also tried user.stripeCustomer = stripeCust I am getting the mongoose object back where it needs to go, but stripeCustomer is not a part of that object! I have verified that stripeCustis, in fact, returning the data I'm expecting it to.

Any guidance? I'm wondering if the Schema is somehow protected, and maybe there's a mongoose way to fix this?

like image 978
Dan Orlovsky Avatar asked Apr 05 '18 01:04

Dan Orlovsky


1 Answers

Disconect the object from mongoose. When making the query use the lean() method of mongoose to get a JSON object. Then you can add keys to it.

http://mongoosejs.com/docs/api.html#query_Query-lean

like image 60
Mohit Mutha Avatar answered Oct 13 '22 13:10

Mohit Mutha