在 NodeJS 中使用 Mongoose + Mockgoose 更新时忽略唯一索引 [英] Unique index ignored when updating with Mongoose + Mockgoose in NodeJS

查看:31
本文介绍了在 NodeJS 中使用 Mongoose + Mockgoose 更新时忽略唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 NodeJS 应用程序中使用 Mongoose ODM 管理与 MongoDB 的数据库连接,并在 Mocha 测试中使用 Mockgoose 拦截连接.我遇到了一个问题,即在更新文档时我的唯一索引被忽略.我只是用另一个名为 Mongoose-bird 的包来包装 Mongoose,它只允许使用 Promise.

I'm currently using Mongoose ODM to manage database connections to MongoDB in a NodeJS application, and intercepting the connection using Mockgoose in Mocha tests. I've ran into an issue where my unique indexes are being ignored when performing an update to a document. I'm simply wrapping Mongoose with another package called Mongoose-bird, which just enables the use of promises.

特别是一种架构如下:

// 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 路径的文档.

When calling Gallery.update(conditions, data, opts) from my controller in a test, purposely setting the slug to be a duplicate of another, it updates the document and then I end up with two documents with the same slug path.

仅供参考,我通过使用 save() 函数找到了解决此问题的方法,该函数似乎毫无疑问地遵守了唯一索引.

FYI, I've found a way around this by using the save() function instead, which seems to obey the unique index without any questions.

但是,由于我更喜欢​​使用 update() 而不是 save()(即每次更新部分文档而不是整个文档),我很想知道其他人是否遇到过同样的问题以及您是如何克服的?

However, as I'd prefer to use update() over save() (i.e. to update documents partially as opposed to the whole document each time), I'm interested to know if anyone else has had this same issue and how you have overcome it?

该应用程序遵循基于 MEAN.js 的标准 MVC 模式,因此它不仅仅是一个模型,但如果我遗漏了任何可能有用的内容,请告诉我.

The application follows a standard MVC pattern based on MEAN.js so there's a bit more to it than just one model, though if I've left out anything which may be useful, please let me know.

更新
在查看 Mockgoose NPM 模块的源代码后,我可以确认在运行 update() 时从未执行针对架构的验证.这里记录了一个问题:http://www.github.com/mccormicka/Mockgoose/问题/58

推荐答案

可能您在测试钩子(例如 afterEach)中使用了 mockgoose.reset.它会删除数据库,并且在执行过程中不会再次创建索引.

Probably you are using mockgoose.reset in a test hook (e.g. afterEach). It drops the database and the indexes aren't created again during the execution.

解决方案是单独删除模型.

The solution is removing models separately.

这篇关于在 NodeJS 中使用 Mongoose + Mockgoose 更新时忽略唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆