[英]Mongoose schema does not work when I try to save it
[英]Mongoose Schema.index on multiple fields does not work with tests
我已经创建了一个uploadSchema
( mongoose.Schema
)与场(休息间):关键和水桶。 他们每个人都不是唯一的,但我希望他们一起创造一个独特的身份。 在我的代码中,我使用了该行(在声明uploadSchema
和在uploadModel
之前):
uploadSchema.index({ key: 1, bucket: 1 }, { unique: true, background: true });
但是,在我的测试( mocha
和chai
)中,索引没有强制执行,所以我可以用相同的密钥和桶创建两个实例(在我的例子中)。 例如,在我的代码中:
await uploadModel.create({ key: testUpload.key, bucket: testUpload.bucket,
name: 'name1', ownerID: USER.id, parent: null }).should.eventually.exist;
在那之后:
await uploadModel.create({key: testUpload.key, bucket: testUpload.bucket,
name: 'name1', ownerID: USER.id, parent: null }).should.eventually.be.rejected;
没有抛出正确的错误错误:
AssertionError: expected promise to be rejected but it was fulfilled with { Object ($__, isNew, ...) }
我没有正确使用它吗? 或者索引和测试有问题吗?
您最有可能在连接中将autoIndex
设置为false(建议这样做)。
将其添加到Schema:
let uploadSchema = mongoose.Schema({ ... }, {autoIndex: true});
但我建议你自己在数据库上自己构建索引,我认为这是最安全的方法。
所以我明白了! 显然,我使用了mongoose.connection.dropDatabase();
在我的后期测试中。 这意味着每次都重置索引。 所以我做的是每次在我的测试中重新创建索引:
before(async () => {
// Remove files from DB
const collections = ['files', 'uploads'];
for (const i in collections) {
mongoose.connection.db.createCollection(collections[i], (err) => {});
}
await mongoose.connection.collections['files'].createIndex({ name: 1, parent: 1, ownerID: 1 }, { unique: true });
await mongoose.connection.collections['uploads'].createIndex({ key: 1, bucket: 1 }, { unique: true });
});
而在之前的每一个:
beforeEach(async () => {
const removeCollectionPromises = [];
for (const i in mongoose.connection.collections) {
removeCollectionPromises.push(mongoose.connection.collections[i].deleteMany({}));
}
await Promise.all(removeCollectionPromises);
});
afterEach为空。 现在它的工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.