Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - how can I make an array in a mongoose schema and push to it

I'm trying to make a ,setchat command in discord.js. It will basically push a channel ID to my mongoDB database but I cant figure out how I can do that

/* eslint-disable no-unused-vars */
const { MessageEmbed } = require('discord.js');
const config = require('../../utils/config.json');
const schema = require('../../models/channelSchema');
module.exports.run = async (client, message, args, utils) => {
    const channel = message.mentions.channels.first();
    if(!channel) return message.channel.send('please mention a channel.');
    schema.channelID.push(channel.id);
    message.channel.send(`chat set as <#${channel.id}>`);
};

but I'm getting cannot read property push of undefined

my schema is

const mongoose = require('mongoose');

module.exports = mongoose.model(
    'channels',
    new mongoose.Schema({
        channelID: [],
    }),
);

any help would be appreciated. Thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because you have to initialize it before you can use it

You can set a default value on the schema

const mongoose = require('mongoose');

module.exports = mongoose.model(
    'channels',
    new mongoose.Schema({
        channelID: {type: Array, default: []},
    }),
);

In that way, it will always be an empty array.

Or you can check if it's empty and initialize it with an empty array before pushing

/* eslint-disable no-unused-vars */
const { MessageEmbed } = require('discord.js');
const config = require('../../utils/config.json');
const schema = require('../../models/channelSchema');
module.exports.run = async (client, message, args, utils) => {
    const channel = message.mentions.channels.first();
    if(!channel) return message.channel.send('please mention a channel.');

    if(!schema.channelID) schema.channelID = [];

    schema.channelID.push(channel.id);
    message.channel.send(`chat set as <#${channel.id}>`);
};

Then, if it's not initialized, it will not appear in the database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...