首页 > 解决方案 > 为什么 updateOne 不能在我的架构上工作?

问题描述

这是我当前的代码:

const mongoose = require("mongoose");
const schema = require("../schemas/ecos");
module.exports = async(req, res) => {
  const db = await schema.findOne({
      RobloxID: req.query.roblox_id
  });
  if(db.IsPendingVerification === "true") {
    res.send({
      success: true
    })
    db.updateOne({
      IsNowVerified: "true"
    })
  }
}

目前它不会更新数据库,所以 IsNowVerified 是真的。为什么会这样?我没有收到任何错误。

我的生态档案:

const mongoose = require("mongoose");
const productSchema = mongoose.Schema({
  Guild: { type: String, default: "" },
  VerifyChannelID: { type: String, default: "" },
  VerifyRoleID: { type: String, default: "" },
  Prefix: { type: String, default: "v-" },
  GuildToken: { type: String, default: "" },
  HasGeneratedToken: { type: Number, default: 0 },
  VerificationLevel1: { type: Boolean, default: false },
  VerificationLevel2: { type: Boolean, default: false },
  VerificationLevel3: { type: Boolean, default: false },
  VerifcationRBLX: { type: Boolean, default: false },
  VerificationRBLXGameLink: { type: Boolean, default: false },
  VerifyMessageWelcomeID: { type: String, default: "" },
  GuildName: { type: String, default: "" },
  GuildInvite: { type: String, default: "" },
  UserID: { type: String, default: "" },
  RobloxID: { type: String, default: "" },
  IsPendingVerification: { type: String, default: "" },
  IsNowVerified: { type: String, default: "" }
});

module.exports = mongoose.model("Eco", productSchema, "ecos");

也就是mongodb数据库的ecos模块导出。

标签: databasemongodbmongoose

解决方案


您的代码有点混乱,所以我更改了一些名称,但功能保持不变:

const mongoose = require("mongoose");
const Eco = require("../schemas/ecos");

module.exports = async(req, res) => {
  const document = await Eco.findOne({
      RobloxID: req.query.roblox_id
  });
  if(document.IsPendingVerification === "true") {
    document.IsNowVerified = "true"
    await document.save()
    res.send({
      success: true
    })
  }

现在我将完成更改:

const Eco = require("../schemas/ecos");

您要导出的不是模式,而是模型。模型是定义数据库ecos集合中条目外观的类。您可能有多个模型,因此最好正确命名它们。

  const document = await Eco.findOne({
      RobloxID: req.query.roblox_id
  });

findOne查询返回的是模型的一个实例,表示在集合中找到的文档。这包含数据库文档中的所有信息,以及许多有用的方法来帮助您修改它。

    document.IsNowVerified = "true"
    await document.save()

您可以直接修改此文档,然后将其保存到数据库中。这将使用您对其所做的任何更改来更新数据库中的文档。

updateOne直接在模型上使用,例如:

    await Eco.updateOne({
      RobloxID: req.query.roblox_id
    }, {
      IsNowVerified = "true"
    })

这通过 查找文档RobloxId,然后更新第二个对象中传递的字段,在这种情况下,IsNowVerified 这很有用,因为它是单个数据库查询,所以它很快。但是由于您要先检查另一个字段,因此最好先找到该文档,然后再对其进行更新。


另一件事是更改"true"true. 这将Boolean在 DB 中使用而不是在 中使用string,它占用的空间要少得多,并且是标准做法,这将导致更少的错误。但是由于您已经在使用该"true"版本,因此更改它可能会导致很多错误,除非您到处更改它。


推荐阅读