创建带有字段ref
的产品时遇到问题。在某些情况下,ref
包含一个唯一值,但是当它没有值时,将其填充为undefined
。因此,当值为undefined
时,就是当我有多个文档作为ref: undefined
时出现猫鼬异常的情况。
字段可以设置为唯一,但允许值重复吗?在这种情况下,该字段为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;
答案 0 :(得分:0)
您可以尝试ref: { type: String, unique: true, trim: true, sparse: true }