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

无法向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 use insertMany() for multiple documents (like your chapters array) or insertOne() 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

  1. Verify MongoDB Service is Running: On Ubuntu, run this command to check if the mongod service is active:
    sudo systemctl status mongod
    
    If it's not running, start it with:
    sudo systemctl start mongod
    
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:43:21