[英]"Cast to Number failed for value " (type Object) - Mongoose
I am working on an endpoint where I want to update the user's game stats: highestScore and totalGamesPlayed.我正在处理一个端点,我想在其中更新用户的游戏统计数据:highestScore 和 totalGamesPlayed。 As far as I can tell, the code should be working.据我所知,代码应该可以正常工作。 However, when making a PATCH request with Postman, I receive this error:但是,当使用 Postman 发出 PATCH 请求时,我收到此错误:
PS.附言。 I am using findOneAndUpdate because save() wasn't working, I wasn't getting the updated version of the user.我正在使用 findOneAndUpdate 因为 save() 没有工作,我没有得到用户的更新版本。
"Cast to Number failed for value \"{ '$max': [ '$userStats.highestScore', 100 ] }\" (type Object) at path \"highestScore\"",
Here's my userModel.js:这是我的 userModel.js:
import mongoose from "mongoose";
const userSchema = mongoose.Schema(
{
username: {
type: String,
required: [true, "Please add a username"],
},
email: {
type: String,
required: [true, "Please add your email"],
},
password: {
type: String,
required: [true, "Please add your password"],
},
userStats: [
{
totalGamesPlayed: {
type: Number,
default: 0,
},
highestScore: {
type: Number,
default: 0,
},
},
],
},
{ timestamps: true }
);
const User = mongoose.model("User", userSchema);
export default User;
My update controller:我的更新 controller:
export const updateUserStats = asyncHandler(async (req, res) => {
// Extract token from headers
const token = req.headers.authorization.split(" ")[1];
// Find the user by token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Find user by id
const user = await User.findById(decoded.id);
if (!user) {
return res.status(404).send("User not found");
}
// Update the user's stats
// Save the updated user
const updatedUser = await User.findOneAndUpdate(
{ _id: decoded.id },
{
$set: {
"userStats.totalGamesPlayed": { $inc: 1 },
"userStats.highestScore": {
$max: ["$userStats.highestScore", req.body.highestScore],
},
},
},
{ new: true }
);
if (updatedUser) {
res.json(updatedUser);
} else {
res.status(400);
throw new Error("Something went wrong");
}
});
It seems like a mix in syntax between update $max and $max (aggregation) (also $inc )这似乎是update $max和$max (聚合) (也是$inc )之间语法的混合
Your call to findOneAndUpdate
should probably look like this:您对findOneAndUpdate
的调用可能如下所示:
const updatedUser = await User.findOneAndUpdate(
{ _id: decoded.id },
{
$inc: {
"userStats.totalGamesPlayed": 1
},
$max: {
"userStats.highestScore": req.body.highestScore
},
},
{ new: true }
);
The syntax you used seems like it belongs to the Aggregation Framework (see Introduction to the MongoDB Aggregation Framework ), where in your case findOneAndUpdate
is an operation with slightly different syntax.您使用的语法似乎属于聚合框架(请参阅MongoDB 聚合框架简介),在您的情况下, findOneAndUpdate
是一种语法略有不同的操作。
In the operation findOneAndUpdate
the $set
operator interprets the syntax you used as if you are trying to assign the Object { '$max': [ '$userStats.highestScore', 100 ] }
as if it was a number to the field $userStats.highestScore
.在findOneAndUpdate
操作中, $set
运算符解释您使用的语法,就好像您试图将Object { '$max': [ '$userStats.highestScore', 100 ] }
当作字段$userStats.highestScore
的数字一样$userStats.highestScore
。 The $max
operator does not work inside $set
(but it would work in the Aggregation Framework). $max
运算符在$set
中不起作用(但它会在聚合框架中起作用)。
Mongodb's more "simple" operations like insert
, find
, findOneAndUpdate
, etc.. only have one stage. Mongodb 更“简单”的操作,如insert
、 find
、 findOneAndUpdate
等只有一个阶段。 The Aggregation Framework allows more sophisticated multi-stage operations.聚合框架允许更复杂的多阶段操作。 These operations work where more context or data is available.这些操作在有更多上下文或数据可用的情况下起作用。 That also means some operators like $max
need to be written slightly differently to make use of additional data or sometimes to avoid ambiguity (and probably for other reasons as well).这也意味着某些运算符(如$max
)需要稍微不同地编写以使用附加数据或有时避免歧义(也可能出于其他原因)。
In the simple operation of findOneAndUpdate
, there's no "direct" access to the current value of the a field.在findOneAndUpdate
的简单操作中,没有“直接”访问 a 字段的当前值。 But an operator like $max
can still do a comparison and work on it.但是像$max
这样的运算符仍然可以进行比较并对其进行处理。 The syntax you used, which would work in an Aggregation Framework stage, opens the door to using values from other fields to calculate the max value.您使用的语法可在聚合框架阶段使用,为使用其他字段的值计算最大值打开了大门。 But it is unavailable for findOneAndUpdate
, so the $max
syntax is simpler and more limited.但它对findOneAndUpdate
不可用,因此$max
语法更简单且限制更多。
"regular" operator: $max “常规”运算符: $max
Aggregation Framework operator: $max (aggregation)聚合框架运算符: $max(聚合)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.