将对象推送到嵌套数组时,Mongoose FindOneAndUpdate 不更新

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

当尝试推送到嵌套数组时,它没有在我的数据库中更新,代码如下:

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 } },
    );

我的架构:

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

知道为什么我的数据库没有更新吗?

我认为您的模型中可能有一些拼写错误:

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

在你的控制器中,你传递的过滤条件不明确,你使用的是哪个guildId?同样,当您调用 guildData.commandLogs 字段更新它时,您缺少括号

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

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

这不会解决您的问题,因为我不知道您遇到了什么样的错误或您的数据库模型,但这些提示已经可以提供帮助。