I followed this SO question to generate an auto-increment sequence field in mongoose.
But on implementing & running the code I get the following error:
TypeError: Cannot read property 'seq' of null
Heres my code below:
Counter.js File
// app/models/counter.js
// load the things we need
var mongoose = require('mongoose');
// define the schema for our user model
var counterSchema = mongoose.Schema({
_id: {type: String, required: true},
seq: {type: Number, default: 0}
});
// methods ======================
// create the model for users and expose it to our app
module.exports = mongoose.model('Counter', counterSchema);
SupportTicket.js File
var Counter = require('../models/counter');
var ticketSchema = mongoose.Schema({
issue: String,
ticketNo: Number,
dateCreated : { type: Date, default: Date.now }
});
ticketSchema.pre('save', function(next) {
var doc = this;
Counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1}}, function(error, counter) {
if(error)
return next(error);
doc.ticketNo = counter.seq;
next();
});
});
I can't figure out why am I getting the "Cannot read property 'seq' of null" Any suggestions?