11

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?

Dan Orlovsky
  • 1,045
  • 7
  • 18

1 Answers1

18

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

Mohit Mutha
  • 2,921
  • 14
  • 25
  • Thank you! I was unaware that mongoose objects cannot be modified like normal objects. :) – Lucas P. Oct 19 '18 at 14:52
  • Is there any way to add a `key` afterwards though? I'm using `find` to get a `Document`. But I cannot use `lean` because I'd like to call `set`. Upon `set`, I'd like to add a `key` to the Object version of the `doc` - but not the `doc` itself. Is this possible? – user2402616 May 26 '20 at 19:15
  • 2
    @user2402616 you can use .toObject() on the returned mongoose document – jc-alvaradov Aug 17 '20 at 09:44