reactjs - 用不同的值在 Mongoose 中更新多个文档——Express Js
问题描述
在为我的应用程序开发后端时,我遇到了一个问题。我使用 Mongoose 在后端运行 Express。我有一个用户模型,就像这样;
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: { type: String, required: true, unique: true, match: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ },
username: { type: String, required: true, unique: true }, // using this one
fullName: { type: String, required: true, unique: true },
password: { type: String, required: true },
points: { type: Number, required: true }, // this one
status: { type: String, require: true }, // & this one
position: { type: String, required: true },
verficationKey: { type: String, required: true }
});
module.exports = mongoose.model('User', userSchema);
现在,我想在许多用户上更新“状态”和“积分”键。但是对于每个用户,他们可能——而且可能会——不同。例如,假设一位用户可能已经有 10 分并且必须获得 +15,而另一位用户可能有 25 分并且必须获得 +5。我想使用他们的“用户名”键在我的数据库中找到我的用户(因为它是独一无二的,我可以通过我的前端轻松访问它)。我根本不知道这是否可能......我对表达和 mongo 有点陌生,所以请耐心等待并解释 - 如果可能的话。
- 我搞砸了
User.updateMany
,甚至User.find().where(...).in(...)
第二个取得了一些进展,但无法将用户保存到我的数据库中,可能写错了:(
- 编辑/更新
这是我目前找到的(某种)运行我需要的代码。但首先它一团糟,其次,它很糟糕。
router.put('/update/points', (req, res, next) => {
User.find().where('username').in(req.body.uid)
.exec()
.then(result => {
var points = req.body.points;
result.forEach((item) => {
points.forEach((user) => {
if (item.username === user[0]) {
item.points = user[1];
item.status = user[2]
item.position = user[3];
item.save()
.then()
.catch()
}
})
})
res.status(200).json({
message: "Success"
})
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
})
})
这是我想出的,但我一点也不满意。在玩了几个小时后,我找到了这个“解决方案”。但显然它很糟糕而且效率低下。
在此之前我做过类似的事情。这个似乎有效,但我讨厌它。
这里还有一个注释。在我的身体中,我从前端发送一个看起来像这样的对象;
{ "uid": ["user1", "user2", "user3"], "points": [["user1", 10], ["user2", 5], ["user3", 25]
] }
因此,有了这个“解决方案”,我别无选择,只能在我的前端编写低效的代码。
解决方案
有什么理由不能将uid
数组和points
数组合并成这样的东西吗?这将使处理服务器上的数据变得更加容易。
[
{ username: "user1", points: 10, status: 8, position: 21 },
{ username: "user2", points: 6, position: 4 },
{ username: "user3", points: 9 },
...
]
然后你可以在服务器上做这样的事情:
router.put('/update/points', async (req, res, next) => {
try {
for (let user of req.body.users) {
let targetUser = await User.findOne({ username: user.username });
if (targetUser) {
// Make the changes and save
targetUser.points = user.hasOwnProperty("points") ? user.points : targetUser.points;
targetUser.status = user.hasOwnProperty("status") ? user.status : targetUser.status;
targetUser.position = user.hasOwnProperty("position") ? user.position : targetUser.position;
await targetUser.save();
}
}
res.status(200).json({
message: "Success"
});
} catch(err) {
console.log(err);
res.status(500).json({
error: err
});
}
});
推荐阅读
- javascript - 更漂亮:禁用 JavaScript 评论的“左键”功能
- bash - 对字符串分隔列表执行处理
- pandas - 附加 GeoDataFrames 不会返回预期的数据帧
- google-chrome - 过去 2 个月,我们在最新的 chrome 浏览器中面临来自 Docusign 的 404 问题
- sql - DB2 如何选择前 2 个月的日期
- tensorflow - tensorflow 服务模型负载影响其他模型图运行尾延迟
- azure-devops - 在 YAML 文件中如何将 SourceDirectory 设置为当前工作目录?
- c++ - 启动更多的 CUDA 线程块是否比启动更少的线程块有更多的开销?
- c# - 如何添加属性数据:对于 json?
- python-3.x - Pandas DataFrame.value_counts() 不允许 dropna=False