I'm an experienced developer teaching myself nodeJS, I'm having some struggles. I've read discussions on the following topic that you will likely refer me to, but they don't seem to work for me. After much trial and error, I'm in the situation described below. I need to maintain some legacy auto-increment fields (not PK, not "_id") in some data I am migrating to mongodb. I want the values to increment in the nodeJS modules so that I achieve the outcome using either postman or my eventual client app.
Here's the sequences collection in the db:
[
{
"_id": "donorId",
"nextValue": 219
},
{
"_id": "donationsId",
"nextValue": 24335
}
]
Here's the schema and helper function:
sequence.js:
const mongoose = require("mongoose");
const sequenceSchema = new mongoose.Schema({
_id: {
type: String,
required: true,
},
nextValue: {
type: Number,
required: true,
},
});
const Sequence = mongoose.model("Sequence", sequenceSchema, "sequences");
module.exports = async function getNextSequenceValue(sequenceName) {
const sequenceDoc = await Sequence.findOneAndUpdate(
{ _id: sequenceName },
{ $inc: { nextValue: 1 } },
{ new: true }
);
return sequenceDoc.nextValue;
}
exports.sequenceSchema = sequenceSchema;
exports.Sequence = Sequence;
====
I cannot set the value of donorId using any of the following approaches. If I call getNextSequenceValue brute force, the value does indeed change in the db.
donors.js:
const { Donor, validate } = require("../models/donor");
const getNextSequenceValue = require("../models/sequence");
const express = require("express");
const router = express.Router();
router.post("/", async (req, res) => {
const { error } = validate(req.body); //currently for debugging just uses Joi.allow();
if (error) return res.status(400).send(error.details[0].message);
// this increments the databasee collection
let nextId = getNextSequenceValue("donorId");
// req.body.donorId = nextId; // this doesn't work either
let donor = new Donor({
donorId: nextId, // does not work //originally: req.body.donorId,
lastName: req.body.lastName,
// more field assignments here
});
// letting donorId get assigned with anything and then overwriting it does not work either
// donor.donorId = getNextSequenceValue("donorId"); //neither does using nextId work here
// donor.donorId = 99; //this DOES work
donor = await donor.save();
res.send(donor);
});
My question is: how do I correctly assign nextValue to donor.donorId during the POST?