简体   繁体   中英

Default Database Data for Mongoose

I'm pretty new to node.js and the MEAN stack, but I'm trying to build an application. In this application, there will be some default data in the database. I'd like this data population to occur when the app is started. So, it basically checks for the default data and creates it if it isn't there. In one case (settings) this is one record where the local settings will be stored. In the other case, it adds several default records to the database by going over an array. I put all this in a module and cal it in server.js, but I have a feeling I'm doing this wrong. It looks like I'm starting to get into callback hell and I'm wondering if I should be using the async library for this or promises or something else all together. Since these db calls actually don't hit before the server is started, it could be a potential issue.

As I said, I'm new to node.js so any input would be awesome. Below is the module and the two functions that are called in server.js when the app is started.

THANKS!

var config = require('./config');
var Settings = require('./app/models/settings')
var Source = require('./app/models/source');

module.exports =
    {
        settings: function () {
            //check to see if any records exists
            Settings.find({}, function (err, settings) {
                if (err)
                    return (err);

                if (settings.length == 0) {
                    //populate default settings
                    var defaultSettings = new Settings();
                    console.log(defaultSettings);
                    defaultSettings.save(function(err){
                        return (err);
                    });
                }
                else {
                    return settings[0];
                }
            });
        },
        sources: function () {
            Source.find({}, function (err, sources) {
                if (sources.length == 0) {
                    defaultSources.forEach(function (item, index) {
                        s = new Source();
                        s.domain = item.domain;
                        s.loginPage = item.loginPage;
                        s.scanUrl = item.scanUrl;
                        s.sourceType = item.sourceType;
                        s.cssSelect = item.cssSelect;
                        s.save(function (err) {
                            if (err) return err;
                        });
                    });
                }
            });
        }
    }


var defaultSources = [
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'TV and Movies',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'TV and Movies',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'Index',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'Search',
        cssSelect: '.post a'
    }
]

I figured it out! There is a lot here, but I basically learned about promises and it changed everything!

var bodyParser = require('body-parser');
var Settings = require('../models/settings');
var Source = require('../models/source');

module.exports = function (app, express) {
    var apiRouter = express.Router();    

    apiRouter.route('/settings')
        .get(function (req, res) {
            //check to see if any records exists
            var settingsPromise = Settings.find({}).exec();
            settingsPromise.then(function (settings) {
                if (settings.length == 0) {
                    var defaultSettings = new Settings();
                    var newPromise = defaultSettings.save(); // might need more error handling here
                    newPromise.then(function () { res.json(defaultSettings) })
                }
                else {
                    res.json(settings[0]);
                }
            })
                .catch(function (err) {
                    res.json({ success: false, message: err })
                })
        })
        .put(function (req, res) {
            var id = req.body.id;
            var promise = Settings.findOneAndUpdate({ _id: id }, req.body).exec();
            promise.then(function (settings) {
                res.json({ status: true, message: 'Settings updated.' });
            })
                .catch(function (err) {
                    res.json({ success: false, message: err });
                });
        });

    apiRouter.route('/sources')
        .get(function (req, res) {
            // show all sources
            var sourcePromise = Source.find({});
            sourcePromise.then(function (source) {
                if (source.length == 0) {
                    // add default sources
                    var addActions = defaultSources.map(defaultPromises) // a handy collection of promises
                    var results = Promise.all(addActions); // wait for them all to complete here with 'Promise.all'
                    results.then(function (data) {
                        res.json(data);
                    })
                    results.catch(function (err) {
                        res.json({ success: false, message: err });
                    })
                }
                else {
                    res.json(source);
                }
            })
                .catch(function (err) {
                    res.json({ success: false, message: err });
                })
        })
        .post(function (req, res) {
            var newSource = new Source();
            var sourcePromise = newSource.save();
            sourcePromise.then(function(source){
                res.json({success: true, message : 'New source added.'})
            })
            .catch(function(err){
                res.json({ success: false, message: err });
            })

        })
    apiRouter.route('/sources/:source_id')
        .get(function (req, res) {
            // show single source
            var sourcePromise = Source.findOne(req.params.source_id).exec();
            sourcePromise.then(function (source) {
                return res.json(source);
            })
                .catch(function (err) {
                    return res.json({ status: false, message: err })
                })
        })
        .put(function (req, res) {
            // show single source
            var sourcePromise = Source.findOneAndUpdate({ _id: req.params.source_id }, req.body).exec();
            sourcePromise.then(function (source) {
                return res.json({ status: true, message: 'Source updated.' });
            })
                .catch(function (err) {
                    return res.json({ status: false, message: err })
                })
        })
        .delete(function(req, res){
            var sourcePromise = Source.findOneAndRemove({_id: req.params.source_id}).exec()
            sourcePromise.then(function(source){
                return res.json({ status: true, message: 'Source deleted.' });
            })
                .catch(function (err) {
                    return res.json({ status: false, message: err })
                })
        })

    return apiRouter;

};

var defaultPromises = function (item) {
    s = new Source();
    s.domain = item.domain;
    s.loginPage = item.loginPage;
    s.scanUrl = item.scanUrl;
    s.sourceType = item.sourceType;
    s.cssSelect = item.cssSelect;
    return savePromise = s.save();
}

var defaultSources = [
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'TV and Movies',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'TV and Movies',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'Index',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'Search',
        cssSelect: '.post a'
    }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM