【发布时间】:2020-06-16 09:12:26
【问题描述】:
我在使用字段 ref 创建产品时遇到问题。在某些情况下,ref 包含一个唯一值,但当它没有值时,将其填充为undefined。因此,当值为undefined 时,当有多个文档为ref: undefined 时,我有猫鼬异常。
是否可以将字段设置为唯一但允许值重复,在这种情况下为未定义或空字符串?
const mongoose = require('mongoose');
const { Schema } = mongoose;
const productSchema = new Schema(
{
ref: { type: String, unique: true, trim: true },
name: { type: String, trim: true, required: true },
price: { type: Number, required: true },
description: { type: String, trim: true, required: true },
}
);
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
【问题讨论】:
-
您可能正在寻找 MongoDB 中的
sparse选项。 docs.mongodb.com/manual/core/index-sparse