【问题标题】:How to import json into MongoDB using Mongoose如何使用 Mongoose 将 json 导入 MongoDB
【发布时间】:2015-08-22 04:47:12
【问题描述】:

我对此有一些问题,这使得它变得棘手,所以......

我正在使用 Mongoose 和 MongoLab,我可以很好地存储和检索数据,但我想要一个允许我做数据库基础种子的系统。

我为集合创建了架构,但由于没有数据,因此没有运行任何架构,因此我似乎无法运行正常的 mongoimport,因为尚未创建集合。

我想向我的节点服务器添加一些内容,以便如果集合不存在或为空,它会加载集合的架构,然后插入种子数据的 json。

所以我有这个...

var Club = require('./schemas/Club');

我通常使用 Club.find 或 Club.save 等,效果很好。

我只想将对象数组保存到它需要创建的 Club 集合中。

我确实研究了 mongoose-fixture,但它已经多年没有更新了,并且可能有一种方法可以做到这一点而无需太多额外的代码,因为我已经定义了架构,并且准备好了 json 数组。

这是我想进行检查和导入时列出的成功事件。

mongoose.connection.on('open', function () {
  console.log('mongoose.connection.opened');
});

另外,考虑一下,如果我想创建两个集合,并且当它为第一个集合中的项目生成 ObjectId() 时,我可以想象想要使用第二个集合中的那些作为参考。

现在假设 Club 对象只有一个字符串属性。

// contents of data/club.json
[
  { 'name' : 'Barcelona' },
  { 'name' : 'Real Madrid' },
  { 'name' : 'Valencia' }
]

非常感谢任何帮助

【问题讨论】:

    标签: json node.js mongodb mongoose


    【解决方案1】:

    如果我理解得很好,您只需将 JSON 文档从 Mongoose 上传到您的 MongoDB 集合。假设您的模型名为Club,您可以通过Club.collection 访问原始驱动程序方法。并使用insertMany 来实现你想要的。

    这是一个独立的例子(有趣的东西在最后):

    > var mongoose = require('mongoose')
    > var assert = require('assert')
    
    > mongoose.connect('mongodb://localhost/test');
    
    > var Schema = mongoose.Schema
    > var clubSchema = new Schema({
    ...   name: String,
    ... })
    
    > var Club = mongoose.model('Club', clubSchema)
    
    // Now, the interesting part:
    > data = [
    ...   { 'name' : 'Barcelona' },
    ...   { 'name' : 'Real Madrid' },
    ...   { 'name' : 'Valencia' }
    ... ]
    > Club.collection.insertMany(data, function(err,r) {
    ...       assert.equal(null, err);
    ...       assert.equal(3, r.insertedCount);
    ... 
    ...       db.close();
    ... })
    

    并从 Mongo Shell 中检查:

    > db.clubs.find()
    { "_id" : ObjectId("5574b464b680174d79e37601"), "name" : "Barcelona" }
    { "_id" : ObjectId("5574b464b680174d79e37602"), "name" : "Real Madrid" }
    { "_id" : ObjectId("5574b464b680174d79e37603"), "name" : "Valencia" }
    

    【讨论】:

      【解决方案2】:

      有时 shell 脚本可能会有所帮助:

      for filename in *; do mongoimport -d mydb -c $filename --jsonArray done
      

      另请参阅:MongoDB Bulk import using mongoimport from Windows folder

      【讨论】:

      • 我们在使用 mongoimport 时遇到的问题是我们只通过 mongoose 适配器验证了我们的数据,而这绕过了它。因此,我们必须检查 json 中的所有字段是否具有正确的格式等,或者将验证构建到我们的 mongodb 架构中
      • 此评论对您的情况无济于事。 :(
      猜你喜欢
      • 2019-07-02
      • 1970-01-01
      • 2019-01-11
      • 2017-08-23
      • 2018-09-05
      • 2019-11-29
      • 2015-09-20
      • 2017-01-02
      • 2015-12-29
      相关资源
      最近更新 更多