user3078441
user3078441

Reputation: 359

Mongoose doesn't create new collection

I have following in server.js :

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

and a model like this one which works fine ! :

    var userSchema = new Schema({
    firstName: { type: String, trim: true, required: true },
    lastName: {type: String, trim: true, required: true},
    cellPhoneNumber : {type: Number, unique: true},
    email: { type: String, unique: true, lowercase: true, trim: true },
    password: String
    });

and there's an another model like below one which doesn't work !

var jobSchema = new Schema({
category: {type: Number, required: true},
title: {type: String, required: true},
tags: [String],
longDesc: String,
startedDate: Date,
views: Number,
report: Boolean,
reportCounter: Number,
status: String,
poster: String,
lastModifiedInDate: Date,
verified: Boolean
});

the two var are as follow :

var User = mongoose.model('User', userSchema);
var Job = mongoose.model('Job', jobSchema);

-- mongod doesn't log any error after server.js is connected to it . Does anybody know what's wrong with my second model ?

Upvotes: 21

Views: 41401

Answers (5)

Tech Ninj
Tech Ninj

Reputation: 31

I am not sure if this is the right answer, but please remember that the name of the .js file must be same as the name of the model. Name the model starting with a capital letter. Name the file starting with a small letter(Usual convention)

Upvotes: 0

matsondawson
matsondawson

Reputation: 748

The reason is, mongoose only auto-creates collections on startup that have indexes in them. Your User collection has a unique index in it, the Job collection does not. I've just had the same problem today.

// example code to test
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

mongoose.model('Test', {
    author: {
        type: String,
        index: true
    }
});

Upvotes: 56

user6951244
user6951244

Reputation:

Another solution for such behavior is adding unique: true in one of Schema objects. It worked for me, mongoose created collection automatically.

For example:

const moviesSchema = new Schema({
 name: {
    type: String,
    required: true // I'm writting about such one
    }
})

Upvotes: 3

Derese Getachew
Derese Getachew

Reputation: 460

First thing to consider is if you have set the autoIndex property on your connection String to True/False;

By default autoIndex property is set to True, mongoose will automatically build indexes defined in your schema when it connects. This is great for development, but not ideal for large production deployments, because index builds can cause performance degradation. If this is the case and collections are still not being created in your database the problem might be something else and not related with indexes.

If you have set autoIndex to false, mongoose will not automatically build indexes for any model associated with this connection i.e. it will not create the collections. In such scenarios you have to manually call model.ensureIndexes(); usually people call this at the same place where they define the models or inside their controllers which in my opinion is bad for production as it does the same thing autoIndex true except this time we are doing it explicitly.

What i recommend is creating a separate node.js process to run ensureIndexes on explicitly and separate it from our main application node.js process.

The first advantage of this approach is i can choose to which models i want to run ensureIndexes() and the second one it doesn't run on startup of the application and degrade my application performance rather i run it on demand.

Below is sample of the code i use to run ensureIndexes on demand.

import mongoose from 'mongoose';
var readline =  require('readline');

//importing models i want 

import category from '../V1/category/model';
import company from '../V1/company/model';
import country from '../V1/country/model';
import item from '../V1/item/model';


//Connection string options

let options = {useMongoClient:true,
autoIndex:false, autoReconnect:true, promiseLibrary:global.Promise};  

//connecting
let dbConnection = mongoose.createConnection('mongodb://localhost:1298/testDB', options);

 //connection is open
 dbConnection.once('open', function () {

        dbConnection.modelNames()
                    .forEach(name => {
            console.log(`model name ${name}`);                                        
            dbConnection.model(name).ensureIndexes((err)=> {
                if(err) throw new Error(err);              
            });

            dbConnection.model(name).on('index',function(err){                
                if (err) throw new Error(err); 
            });                                      
        });

        console.log("****** Index Creation was Successful *******");
        var rl = readline.createInterface({input:process.stdin,output:process.stdout});        
        rl.question("Press any key to close",function(answer){
            process.exit(0);
        });                                   
    });  

Upvotes: 7

JohnnyHK
JohnnyHK

Reputation: 311835

Mongoose won't create the jobs collection for the model until the first document of that model is saved.

Job.create({category: 1, title: 'Minion"}, function(err, doc) {
    // At this point the jobs collection is created.
});

Upvotes: 29

Related Questions