所以我尝试用mongoDB测试一些种子数据,它是一个电子商务商店,我尝试解析一个类别数组,但是它给出了一个错误。
const { Schema, model } = require('mongoose');
const dateFormat = require('../utils/dateFormat');
const productSchema = new Schema({
title: {
type: String,
required: 'The Product title is required',
minlength: 1,
maxlength: 280,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
},
categories: [{
type: Schema.Types.ObjectId,
ref: 'Category',
}],
brand: {
type: Schema.Types.ObjectId,
ref: 'Brand',
required: false
},
image: {
type: String,
required: true,
trim: true,
},
price: {
type: Number,
required: true,
trim: true,
},
createdAt: {
type: Date,
default: Date.now,
get: (timestamp) => dateFormat(timestamp),
}
});
const Product = model('Product', productSchema);
module.exports = Product;
品牌型号:
const { Schema, model } = require('mongoose');
const dateFormat = require('../utils/dateFormat');
const brandSchema = new Schema({
name: {
type: String,
required: 'The Brand name is required',
minlength: 1,
maxlength: 280,
trim: true,
},
products: [{
type: Schema.Types.ObjectId,
ref: 'Product',
}],
createdAt: {
type: Date,
default: Date.now,
get: (timestamp) => dateFormat(timestamp),
}
});
const Brand = model('Brand', brandSchema);
module.exports = Brand;
范畴模型
const { Schema, model } = require('mongoose');
const dateFormat = require('../utils/dateFormat');
const categorySchema = new Schema({
name: {
type: String,
required: 'The Category name is required',
minlength: 1,
maxlength: 280,
trim: true,
},
products: [{
type: Schema.Types.ObjectId,
ref: 'Product',
}],
createdAt: {
type: Date,
default: Date.now,
get: (timestamp) => dateFormat(timestamp),
}
});
const Category = model('Category', categorySchema);
module.exports = Category;
这是种子数据的一小段
{
"title": "Ansie Boots",
"description": "2",
"image": "http://via.placeholder.com/640x360",
"price": 145,
"categories": ["Boots", "For Her"],
"brand":"Vagabond"
}
我正在阅读MongoDB文档,偶然发现了这个$facet文档,但我对它试图做什么有点困惑,因为我仍然是一个初学者。
errors: {
'categories.0': CastError: Cast to [ObjectId] failed for value "[ 'Trainers', 'For Him' ]" (type string) at path "categories.0" because of "CastError"
错误代码显示brands
还
stringValue: '"Nike"',
messageFormat: undefined,
kind: 'ObjectId',
value: 'Nike',
path: 'brand',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
1条答案
按热度按时间vqlkdk9b1#
在产品模型中,
brand
和categories
被定义为引用其他模型的ObjectId。这些字段包含字符串的种子数据。
在引用它们之前,您需要为它们中的每一个创建品牌和类别模型的示例。
如果seed进程是单线程的,您可以使用类似下面的代码来获取品牌文档:
然后用生成的文档替换种子项中的品牌字符串,在创建产品文档之前,对categories数组中的每个条目执行相同的过程。