• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

209
Views
how to set-up default value of variable inside of object in Mongoose schema

I have this schema:

const mongoose = require('mongoose')

const schema = new mongoose.Schema({
  itemDate: {
    type: String,
    required: true,
  },
  itemName: {
    type: String,
    required: true,
  },
  itemPrice: {
    type: Object,
    required: true,

    price: {
      type: String,
      required: true,
    },
    currency: {
      type: String,
      default: 'USD',
    },
  },
})

module.exports = mongoose.model('Item', schema)

and using this mutation for adding item:

  Mutation: {
    addItem: async (_, args) => {
      const { itemName, itemPrice } = args.itemInput
      let { itemDate } = args

      if (!itemDate) {
        itemDate = new Date()
      }
      const item = new Item({ itemDate, itemName, itemPrice })
      await item.save()
      return item
    },

However when adding item, the currency remains null, what am I missing here? I can add the currency in the addItem mutation:

itemPrice.currency = 'USD'

however there must be a better way, isn't that so?

Thanks for your input.

about 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error