我希望这是讨论CRUD问题的正确地方。因此,我正在构建一个MERN电子商务应用程序,在该应用程序中,我创建了猫鼬模式,并与MongoDB连接以存储产品和用户。为了测试我的模式和路由,我使用了Postman,当其他与用户有关的请求照常工作时,我在添加新产品时遇到了一个奇怪的错误,因为这是最重要的特性。
我不知道这个错误是什么,为什么会发生这个错误。
这是我的帖子请求体-
const Product = require("../models/Product");
const router = require("express").Router();
// CREATE PRODUCT
router.post("/", verifyTokenAndAdmin, async (req, res) => {
const newProduct = new Product(req.body);
try {
const savedProduct = await newProduct.save();
res.status(200).json(savedProduct);
} catch (err) {
res.status(500).json(err);
}
});verifyToken是一个JWT令牌。
这是模式
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema(
{
prodId: {
type: String,
required: true,
},
prodName: {
type: String,
required: true,
},
brandName: {
type: String,
required: true,
},
img: {
type: Array,
},
color: {
type: Array,
},
size: {
type: Object,
},
fabricSpecs: {
type: String,
},
model: {
type: String,
},
descDetail: {
type: String,
},
price: {
type: Number,
required: true
},
discount: {
type: Boolean
},
discountAmount: {
type: Number
},
rating: {
type: String
},
review: {
type: Number
},
soldOut: {
type: Boolean
},
category: {
type: String,
},
type: {
type: String,
}
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Product", ProductSchema);下面是邮递员在添加创建另一个产品时显示的错误

也尝试过mongo,但是得到了相同的错误。

发布于 2022-09-19 11:18:50
我真的很感激来自MongoDB社区的Duncan,他帮助我解决了这个问题。
因此,正如面团所描述的那样,很明显,我有一个标题字段,其中有一个唯一的索引,每当我插入一个新文档时,这个索引就会被填充。现在,对于第一个索引,一切都很好,文档被成功插入,但是在那之后,所有的插入都抛出了这个标题字段空错误,如下所示:

我看到的是,在标题字段中有一个独特的索引,用于产品集合。这不会被填充,因此将向文档传递空值,并且集合中已经有一个带有空值的文档。根据您所得到的错误,在标题上有一个唯一的索引。运行
db.products.getIndexes(),您将看到索引。
具有讽刺意味的是,我没有在产品模式中任何时候插入任何名为"title“的字段,那么这是如何发生的呢?
结果表明,MongoDB将允许您在不存在的字段上创建索引。似乎有一段时间在title字段上创建了一个唯一的索引,即使没有文档包含该字段。现在可以通过删除索引来解决这个问题,一切都应该是好的,并且您可以插入多个文档,而不会出现重复的键冲突。
所以我在mongo中运行了db.products.getIndexes()命令,发现他是对的,实际上有一个具有唯一索引值的"title“字段。

根据“面团”,可以通过使用以下命令移除标题字段来修复此问题。
多亏了db.products.dropIndex({"title": 1}),在运行此命令之后,我可以插入多个文档,因为标题字段现在被删除了,唯一唯一的索引是productId,我确保它在插入过程中总是唯一的。
更多关于dropIndex - https://www.mongodb.com/docs/v4.4/reference/method/db.collection.dropIndex/?_ga=2.253559119.714913216.1662801611-1986988651.1652705652的信息
发布于 2022-09-10 21:21:14
错误指示索引title_1已经存在带有{ title : null}的条目。它很可能是唯一的索引,如果条目项是同一标题下的变体,则需要调整标题。
https://stackoverflow.com/questions/73671388
复制相似问题