0

我是一位经验丰富的开发人员,自学 nodeJS,我遇到了一些困难。我已经阅读了有关以下主题的讨论,您可能会向我推荐这些讨论,但它们似乎对我不起作用。经过多次试验和错误,我处于下面描述的情况。我需要在迁移到 mongodb 的一些数据中维护一些遗留的自动增量字段(不是 PK,不是“_id”)。我希望 nodeJS 模块中的值增加,以便我使用邮递员或我最终的客户端应用程序来实现结果。

这是数据库中的序列集合:

[
  {
    "_id": "donorId",
    "nextValue": 219
  },
  {
    "_id": "donationsId",
    "nextValue": 24335
  }
]

这是模式和辅助函数:

序列.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;

====

我无法使用以下任何一种方法设置donorId 的值。如果我调用 getNextSequenceValue 蛮力,则数据库中的值确实会发生变化。

捐助者.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);
});

我的问题是:如何在 POST 期间正确地将 nextValue 分配给donor.donorId?

4

0 回答 0