2

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?

Community
  • 1
  • 1
Skywalker
  • 4,984
  • 16
  • 57
  • 122
  • You missed the `{ "upsert": true, "new": true }` option when creating the new counter entry. The "upsert" is for creation, the "new" is so the modified document is returned, rather than the state before the document was modified. `Counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1}},{ "upsert": true, "new": true }, function(error, counter)` – Blakes Seven Mar 10 '16 at 11:42
  • @BlakesSeven perfect this worked. Thank you so much. learned something new today. – Skywalker Mar 10 '16 at 12:03

1 Answers1

0
counter.findByIdAndUpdate({_id: 'url_count'}, 
{$inc: {seq: 1} }, 
{upsert: true , new: true},  
function(error, counter)

Add This line.This will work fine.

{upsert: true , new: true}
Banana
  • 2,435
  • 7
  • 34
  • 60
Imran Bilal
  • 69
  • 2
  • 9