如何解决insertOne不是功能问题

时间:2019-01-02 02:10:21

标签: node.js mongodb

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/';

MongoClient.connect(url, {useNewUrlParser: true}, function(err, db){

  if(err) throw err;

  var dbo = db.db('mydb');

  var myObj = [{name: 'Company Inc', address: 'Highway 37'}];
  dbo.createCollection('Customers').insertone(myObj, function(err, res){

    if(err) throw err;
    console.log('1 document inserted!');
    db.close();
  });
});

我的代码不起作用,错误是insertOne不是函数。我的mongoDB Shell版本是3.4.18,安装的npm mongodb模块是3.1.10。

1 个答案:

答案 0 :(得分:1)

尝试在不创建集合的情况下插入记录,因为insertOne将自动创建该集合(如果不存在)。

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';
MongoClient.connect(url, {useNewUrlParser: true}, function(err, db){
  if(err) throw err;
  var dbo = db.db('mydb');
  var myObj = [{name: 'Company Inc', address: 'Highway 37'}];
  var collection = db.collection('Customers');
  collection.insertOne(myObj, function(err, res){
    if(err) throw err;
    console.log('1 document inserted!');
    db.close();
  });
});

https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/