【问题标题】:how to read a json file and save entries to mongodb如何读取 json 文件并将条目保存到 mongodb
【发布时间】:2015-11-16 00:49:32
【问题描述】:

我正在解析一个 JSON 文件,它是一个对象数组。我正在尝试用一些逻辑解析这个数组,然后通过 mongoose 将每个条目保存到 mongodb。

var fs = require('fs');
var Promise = require("bluebird");
var Show = require('../server/models/show');

Promise.promisifyAll(fs);

// read file
fs.readFileAsync('upcoming-shows.json', 'utf8')
.then(function (resolve, reject) {
    var shows = JSON.parse(resolve);

    shows.forEach(function(show){
        // first entries have no date
        if(typeof show.date != 'undefined'){
            var formatDate = show.date.split('\n')[1].trim();   // Thu 08 Oct 2015
            show.date = formatDate;

            var newShow = new Show(show);
            newShow.headline = show.headline;
            newShow.eventLink = show.eventLink;
            newShow.eventImage = show.eventImage;
            newShow.venue = show.venue;
            newShow.dateString = show.date;

            // console.log(newShow);
            newShow.save(function(err, s){
                console.log(s);

            });

        }

    });

});

newShow 对象看起来像一个 mongodb 对象

{ dateString: 'Fri 25 Sep 2015',
  headline: 'Gui Boratto',
  eventLink: 'http://www.songkick.com/concerts/24627124-gui-boratto-at-mighty',
  eventImage: 'http://images.sk-static.com/images/media/profile_images/artists/404729/large_avatar',
  date: Fri Sep 25 2015 00:00:00 GMT-0700 (PDT),
  venue: 'Mighty',
  _id: 55d7c0e461ed8df612ad232b,
  artists: [] }

我的猫鼬模型看起来像:

var mongoose = require('mongoose');

// show model schema
var showSchema = mongoose.Schema({

    artists: [{ type : mongoose.Schema.ObjectId, ref : 'Artist' }],
    venueId: { type : mongoose.Schema.ObjectId, ref : 'Venue' },
    date: { type: Date },
    ticketUrl: { type: String },

    headline: { type: String },
    eventLink: { type: String },
    eventImage: { type: String },
    venue: { type: String },
    dateString: { type: String }

});

module.exports = mongoose.model('Show', showSchema);

但是该条目没有保存到 mongodb!为什么没有将数据添加到数据库中?

【问题讨论】:

  • 我建议你仔细检查你的模型,甚至可以在这里发布。如果在调用 save 之前正确输出对象,则问题不在此代码中。
  • @Nocturno 是的,我认为你是对的,问题可能发生在他的 model.js 中
  • 在保存回调函数中,您忽略了 err 变量。我建议检查一下是否返回了错误。

标签: json node.js mongodb mongoose


【解决方案1】:

好的,谢谢您的回复。出现问题是因为我试图在单独的连接上添加到集合中。 This answer 帮助了我。

我在阅读文件之前输入了所有连接信息:

// database connection stuff
var mongoose = require('mongoose');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development',
    envConfig = require('../config/env')[env];
mongoose.connect(envConfig.db);

然后使用节点运行文件本身一次以添加到数据库

【讨论】:

  • 该死的,我几乎想通了,我正朝着那条路线前进。大声笑好地方。那应该可以!
猜你喜欢
  • 2019-09-04
  • 2022-01-25
  • 2017-10-17
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
相关资源
最近更新 更多