[英]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.我正在尝试在 discord.js 中创建一个
,setchat
命令。 It will basically push a channel ID to my mongoDB database but I cant figure out how I can do that它基本上会将频道 ID 推送到我的 mongoDB 数据库,但我不知道该怎么做
/* 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
但我
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
谢谢
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.然后,如果它没有被初始化,它就不会出现在数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.