Home > Net >  Mongoose FindOneAndUpdate not Updating when Pushing an Object to a Nested Array
Mongoose FindOneAndUpdate not Updating when Pushing an Object to a Nested Array

Time:05-16

When trying to push to a nested array it's not updating in my database with the following code:

const obj = {
      key: key,
      user: user,
      description: description,
      date: Date.now(),
      guildId: guildId,
    };

    const guild = await this.GuildModel.findOneAndUpdate(
      { guildId: guildId },
      { $push: { 'guildData.commandLogs': obj } },
    );

My schema:

const GuildSchema = {
  guildId: { type: String },
 
  guildData: {
    commandLogs: [CommandLogsSchema],
  },

Any idea why my database isn't updating?

CodePudding user response:

I think you might have some typos in your model:

 const mongoose = require('mongoose'); 
 const Schema = mongoose.Schema;
 
 const GuildSchema = new Schema({   guildId: { type: String },  
 guildData: {
    commandLogs: [CommandLogsSchema],   })

in your controller, the filter condition that you're passing is not clear, which guildId you are using? also when you call the guildData.commandLogs field to update it you are missing brackets

const filter = { guildId: heretheactualId };
const update = {  { $push: { commandLogs: obj} }};

  const guild = await this.GuildModel.findOneAndUpdate(
       filter,
       update,
    );

this is not going to fix your problem because I don't know what kind of errors you're having or your database model but these tips can already help.

  • Related