目前,我正在使用Mongoose管理NodeJS应用程序中到NodeJS的数据库连接,并在Mocha测试中使用Mockgoose拦截连接。我遇到了一个问题,在执行文档更新时,我的唯一索引被忽略了。我只是简单地用另一个叫做“猫鼬鸟”的包裹包装,它只允许使用承诺。
具体而言,一种模式如下:
// Gallery.js
'use strict';
var mongoose = require('mongoose-bird')(require("mongoose"));
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var deepPopulate = require('mongoose-deep-populate')(mongoose);
var GallerySchema = new Schema({
_id: ObjectId,
type: String,
title: String,
slug: String,
_albums: [{
type: ObjectId,
ref: 'Albums'
}]
});
GallerySchema.index({ slug: 1 }, { unique: true });
GallerySchema.plugin(deepPopulate, {});
mongoose.model('Galleries', GallerySchema);当在测试中从我的控制器调用Gallery.update(conditions, data, opts)时,故意将slug设置为另一个文档的副本,它更新文档,然后我得到两个具有相同slug路径的文档。
FYI,我通过使用save()函数找到了解决这一问题的方法,它似乎遵循唯一的索引,没有任何问题。
但是,由于我更喜欢使用update() over save() (即每次更新文档的一部分而不是整个文档),我很想知道是否还有其他人遇到过同样的问题,以及您是如何克服的?
这个应用程序遵循基于MEAN.js的标准MVC模式,所以它不仅仅是一个模型,尽管如果我遗漏了任何可能有用的东西,请告诉我。
更新
在查看了Mockgoose模块的源代码之后,我可以确认在运行update()时从未执行过对模式的验证。这里有一个记录在案的问题:http://www.github.com/mccormicka/Mockgoose/issues/58
发布于 2016-09-10 08:50:16
可能您正在测试钩子中使用mockgoose.reset (例如,afterEach)。它会删除数据库,并且在执行过程中不会再次创建索引。
解决方案是分别删除模型。
发布于 2019-06-26 09:37:51
添加到迭戈帖子。在测试钩子中调用mockgoose.helper.reset()可能会清除临时存储中的集合,也会删除索引。使用下面的代码段调用reset之后,您应该重置索引。
await mockgoose.helper.reset()
const db = mongoose.connection
db.modelNames().map(async (model) => {
await db.models[model].createIndexes()
})这解决了我的问题。希望这能有所帮助。
发布于 2015-11-08 15:12:26
来自猫鼬文档
当应用程序启动时,Mongoose会自动为模式中的每个定义索引调用ensureIndex。猫鼬将对每个索引依次调用ensureIndex,并在所有ensureIndex调用成功或出现错误时在模型上发出一个“索引”事件。 虽然对开发很有用,但建议在生产中禁用此行为,因为创建索引可能会对性能产生重大影响。通过将架构的autoIndex选项设置为false,或在连接上将选项config.autoIndex设置为false,禁用行为。
由于在开始时设置索引,所以必须调试特定的错误,为什么mongoDb不允许索引,使用下面的代码
//keeping autoIndex to true to ensure mongoose creates indexes on app start
GallerySchema.set('autoIndex', true);
//enable index debugging
GallerySchema.set('emitIndexErrors', false);
GallerySchema.on('error', function(error) {
// gets an error whenever index build fails
});
GallerySchema.index({ slug: 1 }, { unique: true });另外,确保autoIndex没有像mongoose中提到的那样设置为false,或者最好像上面所做的那样显式地设置它为true。
另外,
mongoose.set('debug', true);调试日志将显示它为创建索引而进行的ensureIndex调用。
https://stackoverflow.com/questions/33594499
复制相似问题