Currently, I am in the process of testing some seed data using mongoDB for an ecommerce store. I am encountering an error while trying to parse an array of categories into the products
model.
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;
Brand model:
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;
Category model
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;
In addition, here is a snippet of the seed data that I am working with:
{
"title": "Ansie Boots",
"description": "2",
"image": "http://via.placeholder.com/640x360",
"price": 145,
"categories": ["Boots", "For Her"],
"brand":"Vagabond"
}
While researching MongoDB documentation, I stumbled upon the $facet feature but found it confusing, considering I am still a beginner at this.
errors: {
'categories.0': CastError: Cast to [ObjectId] failed for value "[ 'Trainers', 'For Him' ]" (type string) at path "categories.0" because of "CastError"
The error messages also indicate issues relating to the 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