【问题标题】:Mongoose finds match, but doesn't modifyMongoose 找到匹配项,但不修改
【发布时间】:2020-12-26 07:15:39
【问题描述】:

我是 Mongoose 的新手,不知道如何使用 updateOne() 函数。

    const statusChannelIDSchema = require('../models/statusChannelIDs.js');


    var filter = {guildId: guildId};
    var update = {$set: {statusChannelID: statusChannelID}};
    statusChannelIDSchema.updateOne(filter, update, function(err){
        console.log(err);
    })
    .then(result => console.log(result))
    .catch(err => console.log(err));

console.log(result) 将输出:

null
{ n: 1, nModified: 0, ok: 1 }

所以它匹配,但不修改。不确定“null”在那里做什么。

这是我的 /models/statusChannelIDs.js 文件

const mongoose = require('mongoose');

const statusChannelIDSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    statusChannelID: Number,
    guildId: {
       type: Number,
       required: true,
       unique: true
    },
    userId: Number,
    channelId: Number,
    msgId: Number,
    userName: String
})

module.exports = mongoose.model("statusChannelIDs", statusChannelIDSchema);

我做错了什么?

如何更好地调试猫鼬?

【问题讨论】:

  • 您的 guildId 和 statusChannelID 是符合您架构的 Number 类型,请尝试在 updateOne 中提供相同的类型,而不是 String。
  • @FernandoZamperin 你的意思是这样吗? var filter = {guildId: guildId}; var update = {$set: {statusChannelID: statusChannelID}} 上面的代码返回完全相同的结果我做错了吗?
  • 是的,但两个变量都是数字类型吗?
  • @FernandoZamperin 我用typof检查并确保使用parseInt(),结果仍然相同。
  • 试试这个,看看它是否有效 -> statusChannelIDSchema.findOneAndUpdate(filter, update).then(result => console.log(result)).catch(err => console.log(err )); PS:没有$set

标签: node.js mongodb mongoose discord.js


【解决方案1】:

经过长时间的调试,我终于找到了问题:

  1. 我将它用于 discord.js,它们的 ID 很长(比标准 int 长),因此您必须将它们存储为字符串,否则它们会被解析得很奇怪。
  2. 数据库中的集合不能有大写字母

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2017-12-25
    • 2013-08-15
    • 2016-08-18
    相关资源
    最近更新 更多