无法插入Mongo集合

时间:2018-01-19 15:03:21

标签: javascript node.js mongodb

使用: Ubuntu 17.04 MongoDB 3.6

我刚刚开始学习MongoDB,并在尝试插入文档时遇到了这个问题。我可以连接到数据库但不能插入。这是代码。

var MongoClient = require('mongodb').MongoClient;
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) {
  console.log("Connected correctly to server");
  // Get some collection
  var collection = db.collection(sampleCollection);
  collection.insert(chapters,function(error,result){
    //here result will contain an array of records inserted
    if(!error) {
      console.log("Success :"+result.ops.length+" chapters inserted!");
    } else {
      console.log("Some error was encountered!");
    }
    db.close();
  });
});

我做错了什么?感谢您提供的任何帮助:)

1 个答案:

答案 0 :(得分:0)

您可以使用mongoClient。一种新的更好的连接方式。

有关更多参考资料,请参阅MongoDB Driver Docs.

var MongoClient = require('mongodb').MongoClient;
var connectionUrl = 'MongoDB://localhost:27017',
sampleCollection = 'chapters';

var chapters = [{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
},{
'Title': 'Snow Crash',
'Author': 'Neal Stephenson'
}];

MongoClient.connect(connectionUrl, function(err, client) {
  console.log("Connected correctly to server");
  // Get some collection
  var db = client.db('myproject')
  var collection = db.collection(sampleCollection);

  collection.insert(chapters,function(error,result){
    //here result will contain an array of records inserted
    if(!error) {
      console.log("Success :"+result.ops.length+" chapters inserted!");
    } else {
      console.log("Some error was encountered!");
    }
    client.close()
  });
});