Node.js迁移MongoDB数据到Google Sheets时遇服务账号授权TypeError报错
解决TypeError: doc.useServiceAccountAuth is not a function问题
这个报错核心是你用的Google Sheets客户端库版本/初始化方式不对,下面分两种常用库给你对应解决方案:
情况1:使用官方googleapis库
如果是用Google官方的googleapis包,新版本已经不再通过sheets实例调用useServiceAccountAuth,而是用GoogleAuth单独创建授权对象:
const { google } = require('googleapis'); // 导入你的服务账号凭证文件 const serviceAccount = require('./service-account-key.json'); // 创建授权客户端 const auth = new google.auth.GoogleAuth({ credentials: serviceAccount, // 操作表格至少需要这个权限范围 scopes: ['https://www.googleapis.com/auth/spreadsheets'], }); // 初始化sheets客户端,传入授权对象 const sheets = google.sheets({ version: 'v4', auth }); // 示例:读取表格数据 // const response = await sheets.spreadsheets.values.get({ // spreadsheetId: '你的表格ID', // range: 'Sheet1!A1:C10', // });
情况2:使用google-spreadsheet库(更适合快速操作表格)
如果是用第三方的google-spreadsheet包(v4+版本),要确保doc是正确的GoogleSpreadsheet实例,并且授权参数格式正确:
const { GoogleSpreadsheet } = require('google-spreadsheet'); // 初始化表格实例,传入你的表格ID const doc = new GoogleSpreadsheet('你的Google Sheets表格ID'); const serviceAccount = require('./service-account-key.json'); // 正确授权方式 await doc.useServiceAccountAuth({ client_email: serviceAccount.client_email, private_key: serviceAccount.private_key, }); // 加载表格信息后再操作 await doc.loadInfo(); const sheet = doc.sheetsByIndex[0]; // 获取第一个工作表
额外排查点
- 检查库版本:
google-spreadsheetv3和v4的API差异极大,建议安装最新版并对照官方文档写法。 - 核对凭证格式:服务账号JSON里的
private_key带换行符,复制时别丢失换行。 - 确认变量类型:
doc必须是GoogleSpreadsheet实例,别把授权对象或其他变量错当成doc调用方法。
内容的提问来源于stack exchange,提问作者Hoax
相关产品推荐
相关产品推荐

