猫鼬模型领域独特

时间:2020-06-16 09:12:26

标签: node.js mongodb mongoose

创建带有字段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;

1 个答案:

答案 0 :(得分:0)

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