Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
Mongoose add parentdoc if it doesn't exist OR add subdoc if parent doc exists but subdoc doesn't

Essentially, I have a User that has an email and a list of subscriptions. I want to create the User with the subscription if the user doesn't exist, if the user exists but doesn't have the subscription I Want to simply add the newSubscription to the Users list of subscriptions. Finally, if both User and subscription already exist then I want to handle the existing subscription in my own way.

await UserDocument.findOneAndUpdate(
            {'$and': [{
                'email': email,
            }, {
                'subscriptions.product': product-id,
            }]},
            {'$setOnInsert': newCustomerWithSubscription,
            '$push': {'email.$.subscription': newSubscription}},  
            {upsert: true, new: false},
            async function(err: CallbackError, doc: UserSchemaType | null) {
                //Code to handle if both exists
            }).exec();

DB Design:

User: {
    email,
    subscriptions: [{
        //sub-info
    }]
}
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!