无法向Mongo集合插入数据求助(Ubuntu 17.04 + MongoDB 3.6环境)
Troubleshooting Your MongoDB Insert Issue on Ubuntu 17.04
Hey there! I see you're getting started with MongoDB 3.6 on Ubuntu 17.04 and hitting a snag with inserting documents. Let's walk through the issues in your code and fix them up:
Key Problems in Your Code
- Incorrect Connection Protocol Case: Your connection URL uses
MongoDB://(capital M), but MongoDB requires the protocol to be lowercase:mongodb://. Even if the connection seems to work, this can cause unexpected behavior with database operations. - Deprecated Insert Method: The
collection.insert()method is deprecated in newer Node.js MongoDB drivers (especially when paired with MongoDB 3.6). You should useinsertMany()for multiple documents (like your chapters array) orinsertOne()for single documents instead. - Missing Connection Error Handling: You didn't add a check for connection errors—if the DB connection fails silently, you'd never know why your inserts aren't working.
- Vague Error Logging: Your error message only says "Some error was encountered!" which gives no clues about what went wrong. We need to log the actual error object to debug.
Fixed Code
var MongoClient = require('mongodb').MongoClient; // Fixed protocol to lowercase mongodb:// var connectionUrl = 'mongodb://localhost:27017/myproject', sampleCollection = 'chapters'; var chapters = [{ 'Title': 'Snow Crash', 'Author': 'Neal Stephenson' },{ 'Title': 'Snow Crash', 'Author': 'Neal Stephenson' }]; MongoClient.connect(connectionUrl, function(err, db) { // Handle connection errors first if (err) { console.error("Failed to connect to MongoDB server:", err); return; } console.log("Connected correctly to server"); var collection = db.collection(sampleCollection); // Use insertMany instead of the deprecated insert method collection.insertMany(chapters, function(error, result){ if(!error) { // Use insertedCount instead of ops.length for more accurate feedback console.log("Success: " + result.insertedCount + " chapters inserted!"); } else { // Log the full error to diagnose issues console.log("Error encountered:", error); } db.close(); }); });
Additional Checks to Try
- Verify MongoDB Service is Running: On Ubuntu, run this command to check if the mongod service is active:
If it's not running, start it with:sudo systemctl status mongodsudo systemctl start mongod - Ensure Driver Compatibility: Make sure your Node.js MongoDB driver version works with MongoDB 3.6. Install a compatible version with:
npm install mongodb@3.6
内容的提问来源于stack exchange,提问作者Ben Johnson
相关产品推荐
相关产品推荐

