如何解决Node.js+Express+MongoDB应用中的TypeError: result.select不是函数问题
解决TypeError: result.select is not a function问题
出现这个错误的核心原因是你调用select方法的result不是Mongoose的Query查询对象,而是已经执行完毕返回的文档数组/单个文档对象,普通数组和对象没有select方法。
常见场景及修复方案
场景1:提前执行了查询(用了await)
错误写法:
// await之后,result已经是查询返回的文档数组,不是Query对象 let result = await Product.find({}); if (field) { const sortField = field.split(",").join(" "); result = result.select(sortField); // 数组没有select方法,报错 }
修复写法:先构建查询链,最后再执行await:
// 先创建Query对象,不立即执行查询 let result = Product.find({}); if (field) { const sortField = field.split(",").join(" "); // 链式调用select,Query对象支持该方法 result = result.select(sortField); } // 最后统一执行查询 result = await result;
场景2:使用了原生MongoDB驱动而非Mongoose
如果直接用原生MongoDB驱动,find方法返回的是Cursor对象,没有select方法,需要通过projection参数指定要返回的字段:
if (field) { // 将字段列表转为projection对象格式 const projection = field.split(",").reduce((proj, key) => { proj[key] = 1; return proj; }, {}); result = db.collection('products').find({}, { projection }); }
场景3:查询单个文档(findOne)
如果用findOne并提前await,返回的是单个文档对象,没有select方法,需要把select链式调用在findOne之后:
let result = Product.findOne({}); if (field) { const sortField = field.split(",").join(" "); result = result.select(sortField); } result = await result;
内容的提问来源于stack exchange,提问作者Alice
相关产品推荐
相关产品推荐

