【问题标题】:Mongoose model field unique猫鼬模型领域独特
【发布时间】: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;

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2022-07-22
    • 2015-09-07
    • 1970-01-01
    相关资源
    最近更新 更多