首页 > 解决方案 > 猫鼬模型领域独特

问题描述

我在使用该字段创建产品时遇到问题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;

标签: node.jsmongodbmongoose

解决方案


你可以试试 ref: { type: String, unique: true, trim: true, sparse: true }


推荐阅读