使用空子文档集合保存Mongoose文档会导致重复键错误 [英] Saving Mongoose documents with empty sub-documents collections results in duplicate key error

查看:54
本文介绍了使用空子文档集合保存Mongoose文档会导致重复键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个mongoose模式:

I have two mongoose schemas:

var productSchema = new Schema({
    name: { type: String, required: true, unique: true },
    ...
});
...
var categorySchema = new Schema({
    ...
    products: [ProductSchema]
});

当我尝试保存类别时

var categories = [
    {..., products: []},
    {..., products: []}
];

甚至没有产品

var categories = [
    {...},
    {...}
];

我收到错误

{ [MongoError: E11000 duplicate key error index: test.categories.$products.name_1  dup      key: { : undefined }]
name: 'MongoError',
err: 'E11000 duplicate key error index: test.categories.$products.name_1  dup key: { : undefined }',
 code: 11000,
 n: 0,
 lastOp: { _bsontype: 'Timestamp', low_: 6, high_: 1404282198 },
 ok: 1 }

似乎像mongoose试图保存具有未发现名称的产品。

It seems like mongoose is trying to save products with undefind names.

收到错误之前的Mongoose日志:

Mongoose log before getting error:

Mongoose: categories.insert({ __v: 0, products: [], _id: ObjectId("53b3c167d28a86102dec420a"), order: 1, description: 'Category 1', name: 'Cat 1' }) {}  
Mongoose: categories.insert({ __v: 0, products: [], _id: ObjectId("53b3c167d28a86102dec420b"), order: 2, description: 'Category 2', name: 'Cat 2' }) {}  

如果我从 productSchema <的 name 属性中删除 unique:true / em>两个类别添加了空产品 [] 集合。

If I remove unique: true from the name property of productSchema two categories are added with empty products [] collections.

我做错了什么?

谢谢!

推荐答案

这很正常。空数组基本上被认为是products.name字段的null值,当然这违反了索引的唯一约束。

This is pretty normal really. The empty array is essentially considered to be a "null" value for the "products.name" field, that of course violates the unique constraint on the index.

你可以基本上跳过实际上未定义的名称的任何值,并通过向索引添加稀疏属性来执行此操作。在当前架构路径表单中:

You could essentially "skip" any values of "name" that are in fact undefined, and you do this by adding the "sparse" property to the index. In the present schema path form:

var productSchema = new Schema({
  name: { type: String, required: true, unique: true, sparse: true }
});

var categorySchema = new Schema({
  products: [productSchema]
});

现在,只要名称中没有值,就没有问题,除非它当然是实际上存在于某处。确保首先删除已经创建的索引。

Now as long as there is no value in "name" there will be no problem unless of course it actually exists somewhere. Make sure to drop the index already created first though.

只需注意,请注意这样做是为了确保products.name值是唯一的为整个系列。如果您只是想确保它们对于给定类别是唯一的,那么索引不是您的解决方案,您需要通过其他方式确保。

Just a note, be aware that what this is doing is making sure that the "products.name" values are unique for the "whole" collection. If you are just trying to make sure they are unique for a given category, then indexing is not your solution and you need to ensure that by other means.

这篇关于使用空子文档集合保存Mongoose文档会导致重复键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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