database - 为什么 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模块导出。
解决方案
您的代码有点混乱,所以我更改了一些名称,但功能保持不变:
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"
版本,因此更改它可能会导致很多错误,除非您到处更改它。
推荐阅读
- python - 动态创建的组件无法访问父属性
- python - 如何使带有诗歌和 pyproject.toml 的 python 包的开发环境和生产环境之间的依赖关系保持一致
- javascript - 如何创建两个可重用的调用自定义钩子?
- c - C Makefile 不适用于共享库
- html - 通过vba单击网页中的提交按钮
- python - 为什么我的 python 程序不回复套接字消息?
- ruby-on-rails - 如何使用带有“updated_on”时间戳的 Rails 的 HTTP 缓存助手?
- datatables - 提高与 node().id() 绑定的 jQuery 数据表加载速度
- sql-server - 通过输入不完整的 ID 号从 StudentTable 中获取正确的学生 ID
- r - 如何一次查询具有多个关键字的 Mongo 数据库?