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

187
Views
How to push data with Mongoose to a nested array in MongoDB

I'm trying to push data to a nested array in mongodb. I'm using mongoose as well.

This is just mock code to see if i can get it working:

User model:

import mongoose from "mongoose";

const CoinSchema = new mongoose.Schema({
  coinID: { type: String },
});
const CoinsSchema = new mongoose.Schema({
  coin: [CoinSchema],
});

const WatchlistSchema = new mongoose.Schema({
  watchlistName: { type: String },
  coins: [CoinsSchema],
});

const NameSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  username: { type: String },
});

const UserSchema = new mongoose.Schema({
  name: [NameSchema],
  watchlists: [WatchlistSchema],
  test: String,
});

const User = mongoose.model("User", UserSchema);

export default User;

route:

fastify.put("/:id", async (request, reply) => {
    try {
      const { id } = request.params;
      const newCoin = request.body;
      const updatedUser = await User.findByIdAndUpdate(id, {
        $push: { "watchlists[0].coins[0].coin": newCoin },
      });
      await updatedUser.save();
      // console.dir(updatedUser, { depth: null });
      reply.status(201).send(updatedUser);
    } catch (error) {
      reply.status(500).send("could not add to list");
    }
  });

request.body // "coinID": "test"

I've tried a lot of different ways to push this data but still no luck. I still get 201 status codes in my terminal which indicates something has been pushed to the DB, but when I check nothing new is there.

Whats the correct way to target nested arrays and push data to them?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It's not perfect but you could get the user document, update the user's watchlist, and then save the updated watchlist like so:

fastify.put("/:id", async (request, reply) => {
    try {
        const { id } = request.params;
        const newCoin = request.body;
        
        // get the user
        let user = await User.findById(id);

        // push the new coin to the User's watchlist
        user.watchlists[0].coins[0].coin.push(newCoin);

        //update the user document
        const updatedUser = await User.findOneAndUpdate({ _id: id },
            {
                watchlists: user.watchlists,
            }, 
            { 
                new: true, 
                useFindAndModify: false 
            }
        );
        
        reply.status(201).send(updatedUser);
    } catch (error) {
        reply.status(500).send("could not add to list");
    }
  });
about 4 years ago · Juan Pablo Isaza Report
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!