How to push info into deep nested objects

Hello!
Teach me, my lords, how to put information into a deeply nested object in the database. I tryed everything!

This my schema:

const server = new Schema({
	name: String,
	icon: String,
	owner: String,
	settings: Array,
	users: Array,
	textChannels: Array,
	voiceChannels: Array
})

This code inst work:

const {channelName} = data;
const message = {text, date, username};

await serverModel.updateOne({name: serverName}, {
	$push: {
        [`textChannels.${channelName}.messages`]: {message}
    }
});

This code create duplicate channel every time:

const {channelName} = data;
const message = {text, date, username};

await serverModel.updateOne({name: serverName}, {
	$push: {
       textChannels: {
          [channelName]: {
             messages: {message}
          }
       }
    }
});

Like this:
1

I just want to insert a message object into a messages object. I want all the messages were in one place! I want to be the lord of messages! Help me, please!

And another one question: how do I get rid of the null object (underlined in red) and make the nesting “clean” like internal objects?

I figured out how to make a ‘clean’ attachment. Just need to change the type in the model to Object. But i still isn’t the lord of the messages!

MY FRIENDS! I DID IT!

It’s working:

const server = new Schema({
	name: String,
	icon: String,
	owner: String,
	settings: Array,
	users: Array,
	textChannels: Map,
	voiceChannels: Map
});

await serverModel.updateOne({name: serverName}, {
   $push: {[`textChannels.${channelName}.messages`]: message}
});

2.jpeg

Damn it! I’m fkin the lord of the messages! Thanks a lot to all of you. I spent billion of hours to figure it out! All of you so helped me so much! THANKS A LOT FROM THE RUSSIA WITH LOVE!

1 Like

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