【问题标题】:(Mongoose/MongoDB) Push to empty array? [duplicate](Mongoose/MongoDB)推送到空数组? [复制]
【发布时间】:2019-08-23 07:30:35
【问题描述】:

我的模型中有一个空数组,我试图将数组推送到该数组,但 Compass 没有显示对文档的任何更改。

我尝试在我的模型中将user_list 属性的类型设置为array,以及将其设置为带有[] 的空数组。我还删除并重新创建了整个数据库,以确保它不是内存问题。

型号:

const guildSchema = new Schema({
    guild_name: String,
    guild_id: { type: String, unique: true },
    ...
    user_list: []
})

获取数组并尝试推送:

bot.on("guildUpdate", (oldGuild, newGuild) => {
    let userList = newGuild.fetchMembers().then(function(results){ console.log(results.members.keyArray()); userList = results.members.keyArray();
        Guild.findOneAndUpdate({guild_id: oldGuild.id}, {"$set": {"guild_name": newGuild.name, "guild_icon": newGuild.iconURL}}, {"$push": {"user_list": userList}}, function(err) {
            if (err) throw (err);
        });
    }).catch(console.error)
})

console.log(results.members.keyArray()) 返回我试图推送的简单数组。 Compass 也可以显示使用 $set 进行的更新。尝试推送到 user_list 时出现问题,因为 Compass 在更新时继续只显示一个空白数组。

【问题讨论】:

  • 试试这个。 bot.on("guildUpdate", (oldGuild, newGuild) => { let userList = newGuild.fetchMembers().then(function(results){ console.log(results.members.keyArray()); userList = results.members .keyArray(); Guild.findOneAndUpdate({guild_id: oldGuild.id}, {"$set": {"guild_name": newGuild.name, "guild_icon": newGuild.iconURL,"user_list": userList}}, function( err) { if (err) throw (err); }); }).catch(console.error) })
  • 我相信问题可能出在数组声明上。请张贴数组的样本值。 Mongoose 支持 SchemaTypes 数组和子文档数组。所以,你应该根据需要使用。
  • [ '83041706965995520', '272595023651143681', '547137307535474719', '558039744718569492' ] 这是我要推送的数组的日志。只是一组字符串。

标签: javascript mongodb mongoose discord.js


【解决方案1】:

它不起作用,因为您在 update 查询中添加了 $push 运算符作为第三个参数,它应该是 update 查询的第二个参数的一部分,以及 $set。 #rd 参数用于更新查询选项,例如newupsert

试试这个:

Guild
    .findOneAndUpdate({
        guild_id: oldGuild.id
    }, {
        "$set": {"guild_name": newGuild.name, "guild_icon": newGuild.iconURL},
        "$push": {"user_list": userList} // should be a part of second argument
    }, function(err) {
        if (err) throw (err);
    });

我相信你应该在模式中定义你的数组及其类型。

const guildSchema = new Schema({
    guild_name: String,
    guild_id: { type: String, unique: true },
    ...
    user_list: [String]//if type is String
})

【讨论】:

    猜你喜欢
    • 2019-03-28
    • 2021-02-17
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    相关资源
    最近更新 更多