我正在开发 NodeJs 应用程序,并且正在使用 mongoose 节点包。
示例代码
我正在使用以下方法创建动态集合,这些集合有时无法将数据持久保存在数据库中 -
const Mongoose = require("mongoose");
const Schema = new Mongoose.Schema({
// schema goes here
});
module.exports = function (suffix) {
if (!suffix || typeof suffix !== "string" || !suffix.trim()) {
throw Error("Invalid suffix provided!");
}
return Mongoose.model("Model", Schema, `collection_${suffix}`);
};
我正在使用这个导出的模块来创建基于作为suffix
参数传递的唯一 ID 的动态集合。像这样的东西(跳过不必要的代码) -
const saveData = require("./data-service");
const createModel = require("./db-schema");
// test 1
it("should save data1", function (done) {
const data1 = [];
const response1 = saveData(request1); // here response1.id is "cjmt8litu0000ktvamfipm9qn"
const dbModel1 = createModel(response1.id);
dbModel1.insertMany(data1)
.then(dbResponse1 => {
// assert for count
done();
});
});
// test 2
it("should save data2", function (done) {
const data2 = [];
const response2 = saveData(request2); // here response2.id is "cjmt8lm380006ktvafhesadmo"
const dbModel2 = createModel(response2.id);
dbModel2.insertMany(data2)
.then(dbResponse2 => {
// assert for count
done();
});
});
问题
问题是,测试 2 失败了!API会insertmany
导致 0 条记录未能通过计数断言。
如果我们交换测试的顺序,测试 1 将失败。
如果我分别运行这两个测试,两者都会通过。
如果有 n 个测试,只有第一个测试会通过,剩下的测试会失败。
发现
我怀疑mongoose model creation step
它有问题,因为它使用相同的型号名称,即。Model
同时创建多个模型实例。
我将其更改为以下,并且测试在所有情况下都运行良好-
return Mongoose.model(`Model_${suffix}`, Schema, `collection_${suffix}`);
问题
这给我留下了以下问题-
- 在创建动态集合时,我是否遵循正确的编码约定?
- 可疑代码是否是此问题的实际原因(型号名称也应该是唯一的)?
- 如果是,为什么会失败?(我关注了mongoose 文档,但它没有提供有关模型名称参数唯一性的任何信息。
谢谢。