运行show databases命令时MongoDB新库不显示的问题求助
fuelTracker Database Isn’t Showing Up in show databases Hey there! I’ve run into this exact issue before with Mongoose and MongoDB—here’s what’s going on and how to fix it:
The Root Cause
MongoDB uses a lazy initialization approach for databases and collections. That means simply connecting to a database (like you did with Mongoose) or defining a schema/model doesn’t actually create the database. It only gets created and becomes visible in show databases when you insert the first document into one of its collections.
How to Fix It
You just need to add a small bit of code to insert a test document (or your actual data) into the fuelTracker database. Here’s how to update your existing code:
var mongoose = require('mongoose'); // Add connection success/failure logs to confirm connectivity mongoose.connect('mongodb://localhost/fuelTracker') .then(() => console.log('Successfully connected to MongoDB')) .catch(err => console.error('Connection error:', err)); var Schema = mongoose.Schema; var fuelSchema = new Schema({ time : { type : Date, default: Date.now }, miles : Number, gallons: Number }); var FuelStop = mongoose.model('FuelStop', fuelSchema); // Create and save a test document to trigger database creation const testFuelStop = new FuelStop({ miles: 150, gallons: 6.2 }); testFuelStop.save() .then(() => { console.log('Test document saved! Database should now be visible.'); mongoose.connection.close(); // Optional: Close connection after test }) .catch(err => console.error('Error saving document:', err));
Run this updated code, then go back to your MongoDB shell and run show databases—you’ll see fuelTracker listed now.
Alternative: Create the Database Manually
If you prefer to do it directly in the MongoDB shell instead of via code, run these commands:
use fuelTracker db.fuelStops.insertOne({ miles: 0, gallons: 0 })
The use command switches to the database (even if it doesn’t exist), and insertOne creates the collection and database by writing data.
Quick Checks to Rule Out Other Issues
- Make sure your MongoDB server is running locally on the default port (27017)
- Verify there are no typos in your database name (
fuelTracker) in the connection string - Check that your Mongoose connection isn’t failing (the logs we added will help with this)
内容的提问来源于stack exchange,提问作者208_man

