Search code examples
javascriptnode.jsmongodbmodeling

Basic modeling in Node.js + Mongoose


I'm stuck on developing a node.js application. I'm trying to model a musical scale, which has a name and a number of associated notes:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var scaleSchema = new Schema({
  name: String,
  displayName: String,
  notes: [{type: String}]
});

module.exports = mongoose.model('Scale', scaleSchema);

However, I don't know how to "seed" or even access this model. I want to fill it with some scales which are only ever loaded in once. I know I can require this model and use new to make new entries, but is there a specific part of the node application I have to put this in? Is there a certain best practise to be used? Am I doing this wrong?

I'm pretty confused here, but feel as though I almost have a grasp on how it works. Can someone point me in the right direction?


Solution

  • You can create new database entries like you create objects. Here is a seeder class as an example.

        let mongoose = require('mongoose'),
        User = require('../models/User');
    
        module.exports = () => {
    
        User.find({}).exec((err, users) => {
            if (err) {
                console.log(err);
            } else {
                if (users.length == 0) {
                    let adminUser = new User();
                    adminUser.username = 'admin';
                    adminUser.password = adminUser.encryptPassword('admin');
                    adminUser.roles = ['Admin'];
                    adminUser.save();
    
                    console.log('users collection seeded')
                }
            }
        });
     };
    

    Then in another file you can call it and it will seed your db.

    let usersCollectionSeeder = require('./usersCollectionSeeder');       
    usersCollectionSeeder();
    

    Hope this helps.

    As for structure I like to have a folder called "seeders". In there I have a file called databaseSeeder.js which requires all other seeders like usersCollectionSeeder.js and then calls the functions.

    Here is a sample structure I like to use.

    https://github.com/NikolayKolibarov/ExpressJS-Development