Can't use $push

So I have this code here

const quoteRanking = await quoteRankingSchema.findOne({});

      if (!quoteRanking) {
        return await new quoteRankingSchema({
          guilds: [
            { 
              id: guild.id,
              quotes: [
                { 
                  messageId: msg.id,
                  stars: 0 
                }
              ]
            }
          ]
        }).save();
      };

      await quoteRankingSchema.findOneAndUpdate(
        {
          'guilds.id': guild.id
        },
        {
          $push: {
            'guilds.quotes': { 'messageId': msg.id, 'stars': 0 }
          }
        } 
      );

/*
quoteRankingSchema: {
  guilds: [
    { 
      id: '12345',
      quotes: [
        {
          messageId: '12345',
          stars: 0
        },
        ...
      ]
    },
    ...
  ]
}
*/

And I get this err: “err: MongoServerError: Plan executor error during findAndModify :: caused by :: Cannot create field ‘quotes’ in element {guilds: [ { id: “1066352952983433317”, quotes: [ { messageId: “1146123009380331640”, stars: 0 } ] } ]}”.

I searched on google how to do it an in every example they do the same thing, but mine ain’t working

Does the query run if you run it directly from a shell as opposed to via Mongoose?

How? I don’t know how to do that

If you open a shall prompt onto the sever (mongosh, or compass where you can pop up a shell from the bottom of the screen) or use a 3rd party tool like studio3T you can run a script on its own.

So if you connect it’ll be something like this:

use myDataBaseName
db.getCollection('myCollectionName').findOneAndUpdate(
        {
          'guilds.id': guild.id
        },
        {
          $push: {
            'guilds.quotes': { 'messageId': msg.id, 'stars': 0 }
          }
        } 
      );

When looking into issues like this I always find it easier to isolate moving parts, in your case you’re executing the query through a wrapper, so try and get the query working first and then put it into the wrapper and test again.

Out of interest I did try and put the query straight into a shell and it seemed to work. Can you show the complete document that you’re trying to update based on the ID in your post?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.