【问题标题】:MongoDb TypeError: Cannot read property 'insertMany' of undefinedMongoDb TypeError:无法读取未定义的属性“insertMany”
【发布时间】:2016-12-23 13:56:59
【问题描述】:
import { MongoClient } from 'mongodb';
import assert from 'assert';
import config from './config';


console.log('Inside File');
MongoClient.connect(config.mongodbUri, (err, db) => {
  assert.equal(null, err);


 db.products.insertMany( [
      { item: "card", qty: 15 },
      { item: "envelope", qty: 20 },
      { item: "stamps" , qty: 30 }
   ] ); 
      db.close();

});

对于上面的代码,我得到错误无法读取属性 insertMany of undefined。 但是当我进入下面的时候

 db.products.insertMany( [
      { item: "card", qty: 15 },
      { item: "envelope", qty: 20 },
      { item: "stamps" , qty: 30 }
   ] ); 

在控制台中,产品似乎可以很好地插入数据库。 有人可以告诉我这个问题的原因吗?

【问题讨论】:

  • 试试 db.collection('products')
  • 请在此处查看此答案:stackoverflow.com/a/47662979/5483194 我认为您正在将旧 API 与新版本一起使用,这就是您收到该错误的原因。

标签: node.js mongodb


【解决方案1】:

可以尝试使用db.collection('products').insertMany和callback函数

MongoClient.connect(config.mongodbUri, (err, db) => {
  assert.equal(null, err);

 db.collection('products').insertMany( [
      { item: "card", qty: 15 },
      { item: "envelope", qty: 20 },
      { item: "stamps" , qty: 30 }
   ] , function(error, doc) {
        if(error) {
           console.log(error);
        } else {
           console.log('success');
        }
        db.close();
    }); 
});

【讨论】:

    【解决方案2】:

    insertMany()是一个mongoDB函数,在控制台试一下就可以了,
    但是在 nodeJs 中,您正在处理没有此功能的 Mongoose(mongoDb 驱动程序),要使用 mongoose 存储项目,您需要执行 products.save() 并且它不支持批量插入(您只能在一次)所以你必须经历一个循环:

    var items = [{ item: "card", qty: 15 },
          { item: "envelope", qty: 20 },
          { item: "stamps" , qty: 30 }];
    
    var Products = mongoose.model('Products'); // don't know what you have as a model
    
    for ( var i in items) {
        Products.save(items[i]);
    }
    

    当然你需要处理错误..等等。

    如果您还没有模型,这里有一个 sn-p:

    var Schema = mongoose.Schema; 
    var products = new Schema({
        item : String
      , qty  : int
    });
    mongoose.model("Products", Products);
    

    【讨论】:

    【解决方案3】:

    基本上,您尝试使用的函数 insertMany() 是 MongoDB 函数,可以直接在 mongo 控制台中使用,没有任何问题。但是如果你想通过你的应用程序使用它,这意味着使用 MongoClient 库,你也可以这样做..

    您需要做的非常简单,只需将它与您要插入的集合名称一起使用,并将强制回调 fn() 作为另一个参数传递。

    语法:

    db.collection(<collectionName>).insertMany([{arglist1},{arglist2},
    {arglistn..}],Callbackfn())
    

    我希望一切都会好起来的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      相关资源
      最近更新 更多