Home > Mobile >  How to push data with Mongoose to a nested array in MongoDB
How to push data with Mongoose to a nested array in MongoDB

Time:11-03

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?

CodePudding user response:

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");
    }
  });
  • Related