【问题标题】:Import Json file into Mongoose将 Json 文件导入 Mongoose
【发布时间】:2017-01-02 00:15:22
【问题描述】:

我需要将 JSON 文件导入数据库 Mongoose。这应该是一个应该每天运行的脚本。

我的 JSON 如下:

[
 {
   "grant_title": "name SRL",
   "id": "30579843531",
   "total_amount": "551954"
},{
   "grant_title": "AADI CAPIF ASOCIACION CIVIL",
   "id": "30574449967",
   "total_amount": "37050"
},{
   "grant_title": "LA CAMPAÑOLA S.A",
   "id": "23311183419",
   "total_amount": "139292"
  }
]

我需要将此信息存储在数据库中。

这应该是NodeJS(表达)的脚本。请清楚,因为我是初学者。

【问题讨论】:

  • 你为什么大喊大叫?
  • 对不起,我的英语很差:(。我需要帮助。:)

标签: json node.js mongodb mongoose


【解决方案1】:

让我们循序渐进。首先,您将需要创建一个 CRON 作业,或者使用 NodeJS 调度程序(例如 agenda)以某个时间间隔执行您的函数。

现在...在您的函数中,您需要将 JSON 文件加载到 NodeJS 中。

var json = require('/path/to/file.json');

最后...使用 insertMany 批量插入到您的集合中。

db.collectionName.insertMany(json, function(err,result) {
   if (err) {
     // handle error
   } else {
     // handle success
   }
});

编辑:这是在 NodeJS 中使用议程在每天上午 11:30 运行程序的示例

var Agenda = require('agenda');

startScheduler = function() {
    // Set the scheduler utilizing Agenda
    var agenda = new Agenda({db: {address: 'url/to/database'}});

    agenda.define('RUN AT 1130 AM', function(job, done) {
        // your function goes here...
        done();
    });

    agenda.on('ready', function() {
        // CRON SYNTAX
        // * * * * * *
        // Minute / Hour / Day / Month / Day of week (0-6) Sunday-Saturday
        agenda.every('30 11 * * *', 'RUN AT 1130 AM'); // Run daily at 11:30 AM

        agenda.start();
    });
};

startScheduler();

【讨论】:

  • 在与db.collectionName.insertMany(...) (错误'Cannot read property 'insertMany' of undefined')苦苦挣扎之后,我最终写出了相当于const mongoose = require('mongoose'); /* ... DB connexion ... */ mongoose.connection.db.collection('collectionName').insertMany(...) 的东西.但是我的建议是一种完全无模式的方法(例如,如果您的目标是从可靠的导出中导入数据而不用担心模式声明);在大多数情况下,使用 Mongoose Schema 会更安全。
  • ...此外,如果您使用 Mongoose Schemas,如果您在 JSON 数据中插入日期字符串,它在 Mongo 中仍将具有“日期”类型(而不是存储为原始字符串) .其他数据类型当然也是如此。
猜你喜欢
  • 2019-07-02
  • 2015-08-22
  • 2021-02-26
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多