Telmuun Telmuun - 3 months ago 127
Node.js Question

Auto increment field in mongoose

Im trying to create auto increment field in mongoose but i cant create for some reason

This is my app.js

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Artist = require('./models/artist');
mongoose.connect('mongodb://localhost/auto-increment');

app.get('/', function(req, res){

Artist.create({
name: "Telmuun",
fpimage: "Cover"
}, function(err, artist){
if(err) {
console.log(err);
} else {
artist.save();
console.log(artist);
res.send('Hi ')
}
});
});


// Set Port
app.set('port', (process.env.PORT || 3000));
// Run Server
app.listen(app.get('port'), function(){
console.log('Server has started on Port: '+app.get('port'));
});


and this is my artist model

var mongoose = require("mongoose");
var autoIncrement = require('mongoose-auto-increment');

var artistSchema = new mongoose.Schema({
name: String,
fpimage: String

});

artistSchema.plugin(autoIncrement, 'Artist');
module.exports = mongoose.model('Artist', artistSchema);


When i run the app, i get following the error message

fn(this, opts);
^

TypeError: fn is not a function
at Schema.plugin (C:\Users\tjesu\Desktop\pidal\auto-increment\node_modules\mongoose\lib\schema.js:1060:3)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\models\artist.js:10:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\app.js:4:14)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)


How can i fix this error? What should i do?

Answer

From the docs, it looks like you're missing two things:

You need to initialize autoIncrement:

autoIncrement.initialize(mongoose.connection);

You need to change your call to:

artistSchema.plugin(autoIncrement.plugin, 'Artist');