node.js - 猫鼬模型领域独特
问题描述
我在使用该字段创建产品时遇到问题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;
解决方案
你可以试试 ref: { type: String, unique: true, trim: true, sparse: true }
推荐阅读
- python - 如何在 Python 项目中正确构建内部脚本?
- javascript - 我在反应中使用 scrollLeft 但它没有将它的值设置为元素
- javascript - “$” - 谁先拥有它?jQuery 或浏览器
- r - 如何使用条件表达式的 r 数据名来过滤数据的数据帧?
- ios - 移除 CoreGraphics 动画
- reactjs - 当我在 create-react-app 中输入 npm start 时如何指定自定义 URL
- python - 如何根据世代显示,x '攻击' 和 y '防御'
- javascript - 在加载组件中检查后表达式已更改
- python - 如何修复 Anaconda Jupyter Notebook 内核错误?
- javascript - 使用 React-Native 在 ScrollView 中的特定位置缩放