Mongoose populating empty altas from file.js gives ValidationError because of "BSONTypeError"

Hello everyone, I’m very fresh in the MongoDB world and I’m still trying to grasp it considering I’m very used to SQL. I’m following a course from Brad Traversy about the MERN stack, first time switching to a full javascript envitornment. Naturally MongoDB is used and mongoose package to work with it, I’m asking here for help cause the course is not exactly recent and up-to-date (at least from 1 year ago), so there might be differences im not aware of nowdays.

Here’s the issue, I’m trying to populate an atlas database, I’m already successfully connected to it, I created the Schemas for the models I wanna use, the application is basically a small barebone e-commerce, the problem is found in the products Schema/Importing.
I made a seeder.js file, that aims to populate the database from a static local file in which I have manually inserted products when I started coding. I’m gonna show you both files for context:

seeder.js

connectDB();

const importData = async () => {
  try {
      await Order.deleteMany();
      await Product.deleteMany();
      await User.deleteMany();

      const createdUsers = await User.insertMany(users);
      const adminUser = createdUsers[0]._id;
      const sampleProducts = products.map(product => {
        return { ...product, user: adminUser, slug: product.name.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '') }
      })

      await Product.insertMany(sampleProducts);
      console.log('Data Imported!'.green.inverse)
      process.exit()
  } catch (error) {
      console.error(`${error}`.red.inverse);
      process.exit(1);
  }
};

const destroyData = async () => {
  try {
      await Order.deleteMany();
      await Product.deleteMany();
      await User.deleteMany();

      console.log('Data Destroyed!'.red.inverse)
      process.exit()
  } catch (error) {
      console.error(`${error}`.red.inverse);
      process.exit(1);
  }
};

if(process.argv[2] === '-d') {
    destroyData();
} else {
    importData();
}

products.js

const products = [
  {
    _id: '1',
    name: 'The Legend of Zelda: Breath Of The Wild',
    image: '/images/zelda.jpg',
    description:
      'The Legend of Zelda: Breath of the Wild[b] is a 2017 action-adventure game developed and published by Nintendo for the Nintendo Switch and Wii U consoles. The game is an installment of The Legend of Zelda series and is set at the end of its timeline. The player controls an amnesiac Link, who awakens from a hundred-year slumber, and attempts to regain his memories and prevent the destruction of Hyrule by Calamity Ganon. Similar to the original 1986 The Legend of Zelda game, players are given little instruction and can explore the open world freely. Tasks include collecting various items and gear to aid in objectives such as puzzle-solving or side quests. The world is unstructured and designed to encourage exploration and experimentation, and the main story quest can be completed in a nonlinear fashion. ',
    platforms: ['WiiU', 'Nintendo Switch'],
    category: 'Action-Adventure',
    price: 59.99,
    countInStock: 10,
    rating: 5,
    numReviews: 12,
  },
....
....

Now If I try to run the seeder script, I get back from the console the following error:

ValidationError: _id: Cast to ObjectId failed for value "1" (type string) at path "_id" because of "BSONTypeError"

Which in my ignorance might mean 2 of these things: either there’s a problem with how I structured my products.js file, or theres a problem with the Product Schema itself, that im gonna include now:

productModel.js

const reviewSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  rating: {
    type: Number,
    required: true
  },
  comment: {
    type: String,
    required: true
  },
},{
  timestamps: true,
});

const productSchema = mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User'
  },
  name: {
    type: String,
    required: true
  },
  slug: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true,
  },
  platforms: {
    type: Array,
    required: true,
    default: [],
  },
  category: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
    default: 0
  },
  countInStock: {
    type: Number,
    required: true,
    default: 0
  },
  reviews: [reviewSchema],
  rating: {
    type: Number,
    required: true,
    default: 0
  },
  numReviews: {
    type: Number,
    required: true,
    default: 0
  }


}, {
  timestamps: true
});

//productSchema.plugin(sluggy, { tmpl: '<%name%>' })
const Product = mongoose.model('Product', productSchema);

export default Product;

is there something that was explained in the course when coding these that is different now a year later? I’m almost sure that might be the issue here, Google searching for that error didn’t help much, being somewhat generic, so I ask you guys, I’d appreciate some advice. Thanks to whoever takes the time to take a look.

delete all _id in file products

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.