0

I have a mongoose user schema. seq_no is an auto-incremented field - if the same country and city user is created it is incremented.

const mongoose = require("mongoose");
const AutoIncrement = require("mongoose-sequence")(mongoose);

UserSchema = mongoose.Schema({
  name: String,
  country: String,
  city: String,
  seq_no: Number,
});

UserSchema.plugin(AutoIncrement, {
  id: "user_seq",
  inc_field: "seq_no",
  reference_fields: ["country", "city"],
});

const User = mongoose.model("user", UserSchema);

module.exports = User;
const express = require("express");
const router = express.Router();
const User = require("../models/User");

router.post("/", async (req, res) => {
  try {
    console.log("user post");
    const { name, country, city } = req.body;
    const user = new User({ name, country, city });
    await user.save();
    return res.status(200).json(user);
  } catch (err) {
    console.error(err.message);
    res.status(500).send("Server error");
  }
});

module.exports = router;

I want to reset the counter each day. mongoose-sequence documentations says about counterReset(id, reference, callback) but it throws exception Cannot read property '_resetCounter' of null.

Hiccup
  • 596
  • 6
  • 19

1 Answers1

0

So instead of using the counterReset callback, you can pass an additional reference with the current month year and day to make it a reference field, that way anytime the system detects a new day the plugin automatically resets the counter.

Code would look something like this

const mongoose = require("mongoose");
const AutoIncrement = require("mongoose-sequence")(mongoose);

UserSchema = mongoose.Schema({
  name: String,
  country: String,
  city: String,
  seq_no: Number,
  reset_field: String  // here you pass the current day YYMMDD e.g 220809
});

UserSchema.plugin(AutoIncrement, {
  id: "user_seq",
  inc_field: "seq_no",
  reference_fields: ["country", "city", "reset_field"], //Include your reset field in the references
});

const User = mongoose.model("user", UserSchema);

module.exports = User;

I know this might not address really complicated reset reasons but sure does address my issues hope i'm able to help.

d.bayo
  • 154
  • 4
  • 14