You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js新手使用.get函数时遭遇TypeError问题求助

Fixing "TypeError: item.get is not a function" After Using Mongoose's lean()

Hey there! I totally get why this is confusing—let’s break down what’s happening and how to fix it quickly.

Why the error pops up

When you run Mongoose queries without lean(), the results you get are Mongoose Document instances. These are wrapped objects that come with built-in methods like get(), set(), and save()—that’s why those functions worked perfectly before.

But when you add lean() to your query, Mongoose skips creating those Document instances and returns plain JavaScript objects instead. Plain JS objects don’t have the get() method built into them, which is exactly why you’re seeing that TypeError. Your console.log(docs[1]) showing video.path makes total sense too—the data is still there, just in a simpler, un-wrapped format.

How to fix it

You’ve got two straightforward options depending on what you need:

Option 1: Remove lean() (if you need Mongoose’s helper methods)

If you still want to use get() (maybe for virtual properties, path casting, or other Mongoose-specific features), just take out the lean() call from your query. Your original code will work again because you’ll get Document instances back:

// Without lean() — returns Mongoose Documents
const docs = await YourModel.find();
docs.forEach(item => {
  const videoPath = item.get('video.path'); // This will work!
});

Option 2: Access properties directly (keep lean() for better performance)

If you don’t need Mongoose’s special methods, stick with lean() (it’s faster since it cuts down on overhead!) and just access the property directly instead of using get():

// With lean() — returns plain JS objects
const docs = await YourModel.find().lean();
docs.forEach(item => {
  const videoPath = item.video.path; // No error, and it’s more efficient
});

Quick tip

lean() is awesome for read-only queries where you don’t plan to modify or save the data later. Just keep in mind that plain JS objects don’t have Mongoose’s helper methods, so direct property access is the way to go when using it.

内容的提问来源于stack exchange,提问作者Prithviraj Mitra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:30:22