Node.js报错TypeError: db.model is not a function,求错误原因解析
Hey there! Let's break down this error you're hitting and get to the bottom of what's going wrong.
What does this error mean?
The TypeError: db.model is not a function message tells you that when you tried to call db.model('tasks', Task) in your task.js file, the db variable you're using isn't a valid Mongoose database connection instance.
Mongoose is the library that provides the .model() method to define MongoDB models—if your db object comes from somewhere else (like the raw MongoDB native driver, or a failed connection), it won't have this method attached.
Common Causes & Fixes
Let's go through the most likely reasons this is happening, and how to fix them:
You're using the raw MongoDB driver instead of Mongoose
If your database connection code uses the nativemongodbpackage instead of Mongoose, the resultingdbobject won't have the.model()method. Mongoose adds this abstraction layer for defining models, which the native driver doesn't include.
Fix: Switch to using Mongoose for your connection and model definitions. Here's a quick example:// In your connection file (e.g., db.js) const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/your_database_name', { useNewUrlParser: true, useUnifiedTopology: true }); module.exports = mongoose; // Export the Mongoose instance directlyThen in your
task.js:const mongoose = require('../path/to/db.js'); // Import the Mongoose instance const TaskSchema = new mongoose.Schema({ // Define your task fields here (e.g., title: String, completed: Boolean) }); module.exports = mongoose.model('tasks', TaskSchema); // Use mongoose.model directlyYou're exporting the wrong object from your connection file
If your connection file exports a raw database object (likeclient.db()from the native driver) instead of the Mongoose instance, thatdbwon't have.model().
Fix: Double-check your connection export—make sure you're exporting the Mongoose object, not a native driver db instance.Your database connection isn't fully established when you call
.model()
If you're trying to define the model before Mongoose finishes connecting to MongoDB, thedbobject might not be initialized properly.
Fix: Mongoose handles this automatically if you use the global Mongoose instance (like the examples above). It will queue model definitions until the connection is ready, so you don't need to wait for aconnectedevent manually.
Checking Your Code
Looking at your error stack, the problem is at /var/www/html/mongo/crud/src/model/task.js:11 where you return db.model('tasks', Task). Start by verifying where that db variable is coming from—trace back to how you imported it, and confirm it's a valid Mongoose instance.
内容的提问来源于stack exchange,提问作者DavSev

