Mongodb field autoincrement (not ID)

Asked

Viewed 55 times

-2

Hello, I have difficulty using an auto-increment function in a numeric field on Mongodb (is not ID).
The code is in nodejs with Mongoosis and no use plugin Mongoose-autosequence etc.
The structure of the project is route-controller-model.
The route passes the req.body for the controller;
The Controller creates the document in the database;
The model contains only the Schema. The function nextval is used in the controller, which must get a new number for the number field before creating the document.

The function nextVal goes into the counters collection, increments 1 to Quence and returns the field value (nextVal.js file):

import { db } from '../models/index.js';
const Counter = db.counterModel;

const nextVal = async (seqName) => {
  var seqDoc = await Counter.findAndModify({
    query: { _id: seqName },
    update: { $inc: { sequence_value: 1 } },
    new: true
  });
  return seqDoc.sequence_value;
};
export default { nextVal };

The controller receives the req.body and persists in the collection request. Use async Function, but is not accepting the nextVal(). The mistake says nextVal is not Function:

import { db } from '../models/index.js';
import nextVal from './nextVal.js';
const Pedido = db.pedidoModel;

const create = async (req, res) => {
  // Cria um Pedido com itens de pedido
  const pedido = new Pedido({
    numero: nextVal('pedido'),
    descricao: req.body.descricao,
    dped: Date.now()
  });

  // Save pedido in the database
  Pedido.create(pedido, (err, data) => {
    if (err)
      res.status(500).send({
        message:
          err.message || "Erro ao criar o pedido."
      });
    else res.send(data);
  });
};

The model:

export default (mongoose) => {

  const schema = mongoose.Schema({
    numero: { type: Number, required: false },
    descricao: { type: String, required: false },
    dped: { type: Date, required: false, default: Date.now }
  });

  schema.method('toJSON', function () {
    const { __v, _id, ...object } = this.toObject();
    object.id = _id;
    return object;
  });

  const pedidoModel = mongoose.model('pedido', schema, 'pedido');
  return pedidoModel;
};

I researched other similar questions, but I couldn’t apply them in my case. They use pre-save, or do direct db.collection in the mongodb. Please ask for help on how to use the function in the controller.

1 answer

0


follows the solution to the 2 problems:

  1. Mongoose does not accept Finfandmodify; I must replace it with Findandupdate (with proper parameter adjustments);

  2. Regarding the use definition of the nextVal function():

2.1 The function must be async / await (code below after responses). I have put the function in the controller scope (instead of importing); 2.2 Function call shall be preceded by await (below code after function).

The nexVal() function was thus declared and used within the controller:

const Counter = db.counterModel;

async Function nextVal(seqName) { var seqDoc = await Counter.findAndUpdate( { _id: seqName }, { $inc: { sequence_value: 1 } }, { new: true } ); Return seqDoc.sequence_value; };

and the call to function went like this:

const create = async (req, res) => { // Create an Order with order items const pedido = new Pedido({ number: await nextVal('request'), Description: req.body.Description, dped: Date.now() });

I’m gonna shut this down.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.