Basic modeling in Node.js + Mongoose

63 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

You might want to look into .create() a mongoose function.

I'm not sure if this is the only way to do it, but you might want to add something like

var Scale = mongoose.model("Scale", scaleSchema);
module.exports = Scale; //instead of what you currently have for you last line

Then you can do something like

 Scale.create({name: varThatHasValName,
             displayName: varThatHasValdisplayName,
             notes: varThatHasValnotes}, function (err,scale));

In another part of your code when you want to make a new scale.

I've recently used node and mongoose for a class, but I'm not an expert, but this is probably what I'd do (if I'm understanding your question).