NullEins
NullEins

Reputation: 101

Autoincrement with Mongoose

I'm trying to implement an autoicremental user_key field. Looking on this site I came across two questions relevant for my problem but I don't clearly understand what I should do. This is the main one

I have two Mongoose models, this is my ProductsCounterModel.js

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

var Counter = new Schema({
_id: {type: String, required: true},
sequence_value: {type: Number, default: 0}
});

module.exports = mongoose.model('products_counter', Counter);

and this is the Mongoose model where I try to implement the auto-increment field:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var products_counter = require('./ProductsCounterModel.js');

var HistoricalProduct = new Schema({
product_key: { type: Number },
class: { type: String },
brand: { type: String },
model: { type: String },
description: { type: String }
});

HistoricalProduct.pre("save", function (next) {
console.log("first console log:",products_counter);
var doc = this;
products_counter.findOneAndUpdate(
    { "_id": "product_key" },
    { "$inc": { "sequence_value": 1 } },
  function(error, products_counter)   {
    if(error) return next(error);
    console.log("second console log",products_counter);
    doc.product_key = products_counter.sequence_value;
    next();
});
});

module.exports = mongoose.model('HistoricalProduct', HistoricalProduct);

Following the steps provided in the above SO answer I created the collection products_counter and inserted one document.

My document

The thing is that I'm getting this error when I try to insert a new product: "TypeError: Cannot read property 'sequence_value' of null"

This are the outputs of the above console logs.

first console log output:

function model (doc, fields, skipId) {
if (!(this instanceof model))
  return new model(doc, fields, skipId);
Model.call(this, doc, fields, skipId);
}

second console log:

Null

can you see what I'm doing wrong?

Upvotes: 1

Views: 301

Answers (1)

mickl
mickl

Reputation: 49945

You can run following line in your middleware:

console.log(products_counter.collection.collectionName);

that line will print products_counters while you expect that your code will hit products_counter. According to the docs:

Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. Set this option if you need a different name for your collection.

So you should either rename collection products_counter to products_counters or explicitly configure collection name in your schema definition:

var Counter = new Schema({
    _id: {type: String, required: true},
    sequence_value: {type: Number, default: 0}
}, { collection: "products_counter" });

Upvotes: 1

Related Questions