Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Created November 1, 2021 20:32
Show Gist options
  • Save Avi-E-Koenig/c3f91cf3c67b9247067866d2a420d02e to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/c3f91cf3c67b9247067866d2a420d02e to your computer and use it in GitHub Desktop.
Add or create document in nested array mongoose
const Cart = require('../models/cart.model')
// returns ObjectId or null
const { parseObjectId } = require('../utils/validateObjectId')
async function addOrCreateNestedItem(newItem) {
try {
const cart = await Cart.findOne(
{
_id: '618018504bb0eb2bdf6f2955',
})
const targetItem = cart.items.find(item => {
return item.product_id.equals(parseObjectId(newItem.product_id))
})
if (targetItem) {
targetItem.amount = newItem.amount
} else {
cart.items.push(newItem)
}
cart.markModified('items')
const newCart = await cart.save()
console.log("๐Ÿš€ ~ file: testAddOrEditItem.js ~ line 24 ~ main ~ newCart", newCart)
} catch (error) {
console.log("๐Ÿš€ ~ file: testAddOrEditItem.js ~ line 26 ~ main ~ error", error)
}
}
// example use
addOrCreateNestedItem({
product_id: '617fe683974a15542b747ca1',
amount: 66
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment