简体   繁体   English

“为值转换为数字失败”(类型对象)- Mongoose

[英]"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 )之间语法的混合

tl;dr tl;博士

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 }
  );

explanation解释

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 更“简单”的操作,如insertfindfindOneAndUpdate等只有一个阶段。 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.

相关问题 猫鼬-在路径上值“ [object Object]”的转换为数字失败 - mongoose - Cast to number failed for value “[object Object]” at path $divide 是 mongoose 给出“Cast to Number failed for value” - $divide is mongoose is giving "Cast to Number failed for value" Mongoose - CastError 转换为字符串失败的值“对象” - Mongoose - CastError Cast to string failed for value "Object" mongoose.js CastError:对于路径“未定义”的值“[object Object]”,转换为数字失败 - mongoose.js CastError: Cast to number failed for value “[object Object]” at path “undefined” 消息:'在nodejs mongoose express中的路径中,为数字转换为数字失败“undefined” - message: 'Cast to number failed for value “undefined” at path in nodejs mongoose express Mongoose:转换为ObjectId失败的值 - Mongoose: Cast to ObjectId failed for value CastError:对于 model“用户”的路径“profile.age”中的值“{'$lte':'100'}”(类型对象),转换为数字失败 - CastError: Cast to Number failed for value "{ '$lte': '100' }" (type Object) at path "profile.age" for model "User" 路径“markupPercentage”处的值“NaN”(类型编号)转换为数字失败 - Cast to Number failed for value "NaN" (type number) at path "markupPercentage" Mongoose 转换为 ObjectID 的值失败了......但为什么 - Mongoose cast to ObjectID failed for value... but why Mongoose DBrefs - 转换为ObjectId失败的值 - Mongoose DBrefs - Cast to ObjectId failed for value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM