Mongoose resolves references (ref) automatically when using .populate(), but if you need to query the referenced model directly, you must import it.
CASE 1 - When You DON'T Need to Import RoleModel If you're only populating the role field inside a UserModel query, Mongoose handles the reference automatically.
import UserModel from "@_models/user"; async function getUsersWithRoles() { const users = await UserModel.find().populate("role"); // No need to import RoleModel return users; }
Here, Mongoose knows role references Role and fetches the related data.
CASE 2 - When You NEED to Import RoleModel If you're performing a direct query on the RoleModel, you must import it.
import RoleModel from "@_models/role"; async function findAdminRole() { const adminRole = await RoleModel.findOne({ name: "Admin" }); // Direct query on RoleModel return adminRole; }
Since this query only involves the Role collection, Mongoose needs RoleModel explicitly.