-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.