在 Mongoose 中更新多个文档,每个文档具有不同的值 -- Express Js
Updating Multiple Documents In Mongoose With Different Values Each -- Express Js
我在为我的应用程序开发后端时遇到了问题。我 运行 在后端用 Mongoose 表达。我有一个用户模型,是这样的;
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(...)
第二个取得了一些进展,但无法将用户保存到我的数据库中,可能写错了:(
- 编辑/更新
这是我目前为 (kind-of) 运行 找到的我需要的代码。但首先是一团糟,其次,它很糟糕。
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
})
})
})
这是我的想法,但我一点都不满意。玩了几个小时后,我找到了这个“解决方案”。但显然它很糟糕且效率低下。
之前我做过类似的事情。这个似乎有用,但我讨厌它。
这里还要注意一下。在我的 body 中,我发送了一个 object 从我的前端看起来像这样的东西;
{
“uid”:[“用户 1”,“用户 2”,“用户 3”],
“点”:
[
[“用户 1”, 10],
[“用户 2”, 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
});
}
});
我在为我的应用程序开发后端时遇到了问题。我 运行 在后端用 Mongoose 表达。我有一个用户模型,是这样的;
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(...)
第二个取得了一些进展,但无法将用户保存到我的数据库中,可能写错了:(
- 编辑/更新
这是我目前为 (kind-of) 运行 找到的我需要的代码。但首先是一团糟,其次,它很糟糕。
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
})
})
})
这是我的想法,但我一点都不满意。玩了几个小时后,我找到了这个“解决方案”。但显然它很糟糕且效率低下。
之前我做过类似的事情。这个似乎有用,但我讨厌它。
这里还要注意一下。在我的 body 中,我发送了一个 object 从我的前端看起来像这样的东西;
{ “uid”:[“用户 1”,“用户 2”,“用户 3”], “点”: [ [“用户 1”, 10], [“用户 2”, 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
});
}
});