Created
November 1, 2021 20:32
-
-
Save Avi-E-Koenig/c3f91cf3c67b9247067866d2a420d02e to your computer and use it in GitHub Desktop.
Add or create document in nested array mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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