如何为返回的Mongoose对象添加Stripe客户对象键值对?
嘿,我来帮你搞定这个需求,顺便优化下代码里的回调嵌套问题~
首先,你的核心需求是把Stripe返回的客户对象附加到Mongoose查询出来的Platform对象上对吧?原代码的思路没问题,但回调嵌套的写法既不优雅也容易遗漏错误处理,我给你两种实现方案:
方案一:用Async/Await简化代码(推荐)
现在Node.js和Stripe库都支持Promise,用async/await能让代码逻辑更清晰:
exports.getPlatformByCId = async (cId) => { try { // 假设clientId是唯一标识,用findOne直接获取单个文档更高效 const user = await Platform.findOne({ clientId: cId }); if (!user) { throw new Error('找不到对应clientId的Platform记录'); } // Stripe方法不传回调会自动返回Promise,直接await即可 const stripeCust = await stripe.customers.retrieve(user.stripeCustomerId); // 把Stripe客户对象附加到Mongoose对象上 // 如果只是返回给前端用,直接加属性就行;如果要存数据库,得先在Schema里定义对应字段 user.stripeCustomer = stripeCust; return user; } catch (err) { // 把错误抛出去,让调用方统一处理 throw err; } };
方案二:修复原有的回调写法
如果你暂时不想用async/await,也可以补全原代码的错误处理逻辑:
exports.getPlatformByCId = (cId) => { return new Promise((resolve, reject) => { Platform.find({ clientId: cId }) .then(response => { if (!response || response.length === 0) { return reject(new Error('找不到对应clientId的Platform记录')); } let user = response[0]; stripe.customers.retrieve(user.stripeCustomerId, (err, stripeCust) => { if (err) { // Stripe调用出错时要reject Promise return reject(err); } // 附加Stripe客户对象后resolve user.stripeCustomer = stripeCust; resolve(user); }); }) .catch(dbErr => { // 捕获数据库查询的错误 reject(dbErr); }); }); };
几个关键注意点:
- 尽量用
findOne替代find:如果clientId是唯一的,直接获取单个文档比取数组第一个元素更合理,也能避免数组为空的问题。 - 错误处理要全面:不管是数据库查询失败,还是Stripe API调用出错,都要正确传递错误,避免Promise一直处于pending状态。
- 保存到数据库的额外操作:如果需要把附加的stripeCustomer永久存在数据库里,得先在你的Platform Schema中添加对应的字段(比如
stripeCustomer: Object),然后调用await user.save()。
内容的提问来源于stack exchange,提问作者Dan Orlovsky
相关产品推荐
相关产品推荐

