Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 856
user3078441 Avatar asked Jul 24 '15 18:07

user3078441


People also ask

Does Mongoose automatically create collection?

exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.

Does MongoDB automatically create collections?

MongoDB creates collections automatically when you insert some documents. For example: Insert a document named seomount into a collection named SSSIT. The operation will create the collection if the collection does not currently exist.

Can I use Mongoose without schema?

You can use Mongoose with the collections that have schema and the node driver or another mongo module for those schemaless ones.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ). If you don't want to use this version key you can use the versionKey: false as mongoose.


1 Answers

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
    }
});
like image 93
matsondawson Avatar answered Sep 23 '22 20:09

matsondawson