简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM