如何读取json文件并将条目保存到mongodb

时间:2015-08-22 00:29:44

标签: json node.js mongodb mongoose

我正在解析一个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!为什么不将数据添加到数据库中?

0 个答案:

没有答案