Attempting to populate mongoDB with an array of strings, unsure of how to define the model for this

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

Answer №1

The Product model defines brand and categories as ObjectIds that point to other models.

In the initial data, these fields are filled with strings.

You must first create instances of the Brand and Category models for each before you can reference them.

If the seeding process will be done in a single thread, you could use something similar to this code snippet to retrieve a brand document:

let branddoc = Brand.findOne({name: seedItem.name});
if (branddoc == null) { 
   branddoc = new Brand({name:seedItem.name})
   branddoc.save()
}

After replacing the brand string in the seed item with the generated document, repeat the same procedure for each entry in the categories array before creating the product document.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

nyroModal automatically adapts its dimensions according to the size of the webpage, not the size of

A situation has arisen with a link that opens an image using nyroModal. While everything is functioning correctly, the Modal window appears in the center of the page instead of aligning with the middle of the browser window. As a result, only the upper por ...

The casperjs evaluate function isn't able to provide me with the necessary data I

Having trouble getting my function to return data correctly. I am trying to retrieve the value of this input box. <input type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6e736a667b6764646025686466">[em ...

Encountering a connectivity issue with the MongoDB server

While I wrote my server IP on the mongoose connection string, I am unable to insert data into MongoDB. How can I resolve this issue? var express = require("express"); var app = express(); var mongoose = require('mongoose'); mongoose.connect(&ap ...

Use jQuery to change the date format from Feb 17, 2012 to 17/02/2012

Here is the code snippet I am working with: let Date = "Feb 17, 2012"; Is there a way to transform it into Date = "17/02/2012" by utilizing jQuery? ...

Steps to prevent specific links from being clickable in React Native's webview component

In my React Native app, I am utilizing the react-native-webview component to display blog posts. The code I have implemented is straightforward, but my goal is to restrict the webview to only show content from the blog section of the website, preventing us ...

The div is not displaying the conditional styling as expected

I need help with mapping an array of cards wrapped in a div. I want the first, second, second-to-last, and last divs to go on a new line or take up the entire row. My project is in Vue3 and I'm using the PrimeVue component library. <div class=" ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. https://i.sstatic.net/MRsJ2.png ...

Having trouble saving an object using mongoose's findOne and save methods?

Here is the model I am working with: GigSchema = new Schema({ lastUpdate: { type: Date, "default": null }, type: { type: String, "default": null, "enum": [null, 'mvp', 'code-review', 'extension', &ap ...

Clearing console logs in webkit: A step-by-step guide

Does anyone know how to clear the console in webkit? I have a function that displays debug data in the console, but it becomes difficult to read due to the number of lines. Is there a simple way to empty the console? When I check the console itself, I onl ...

Restrict magnification in THREE.js mousewheel interaction

Seeking advice on limiting zoom in and out of a model in three.js. I have explored trackball controls, but couldn't find a way to restrict zooming. I also experimented with orbit controls, but encountered issues when combined with trackball controls r ...

What is the best way to update a prop value using a different function?

I have a single component in my NextJs application and I am trying to modify the child prop (referred to as type) of the child component when the <input> element is empty. However, I am facing issues with this task. Can someone please assist me? Tha ...

The creation of the 'id' field within the {buffHave: []} element is not possible

I'm encountering an issue when trying to push data for id and duration to buffhave. The error message says "Cannot create field 'id' in element {buffHave: []}". const { Schema, model } = require("mongoose"); const schema = new Schema({ use ...

What is the best way to eliminate specific elements from an array of objects in MongoDB aggregate based on a condition?

I have a database of documents called ChatRooms stored in MongoDB with the following structure: { _id: ObjectId('4654'), messages: [ { user: ObjectId('1234'), sentAt: ISODate('2022-03-01T00:00:00.000Z') ...

Selecting Objects with a Mouse in Three.js

Thanks to the wonderful support from the stackoverflow community, I was able to successfully implement a basic object picking example. You can view the functional code here. However, it's important to note that this example specifically works when t ...

Strategy for refreshing a Polymer application

Our application is a Polymer 2 single-page app that incorporates custom build steps to create versioned resource files using gulp-rev-all. Everything is functioning properly, but we are now looking to implement a secure way of refreshing the application. C ...

Concealing the source code within a Next.js application

Currently, I am utilizing next.js for a project. We have a contact page where we display email addresses in cards, but we want to prevent bots from accessing this information. A solution was discovered by one of my colleagues to hide the email addresses i ...

Comparing two numerical values within an array of objects in MongoDB

Currently, I am working with MongoDB and have the following data structure: { "_id" : ObjectId("5a868d785e5436aeed0502c0"), "symbol" : "ABC", "values" : [ { "High" : 53.0, "Close" : 51.85, "Open" : 50.8 }, { " ...

500 Internal Server Error in Laravel 5.4 due to AJAX Request

I am currently utilizing ajax to store my data in the database within laravel 5.4 so that I can avoid refreshing the page or redirecting elsewhere when saving data. However, I keep encountering an internal server error 500. As a newbie to ajax, I suspect t ...

Steps for populating an ng-table with data retrieved from a REST web service that returns a JSON format

I am currently facing an issue while trying to load my table from a JSON response that I receive from REST web services in SpringMVC. The error message I received indicates that my REST method does not support the GET request. The URL mapped in my control ...