终端中的数字未定义或 NaN

问题描述 投票:0回答:1

我在mongo中有数据。我从 mongo 获取这些数据到屏幕。然后我想通过 onClick 更新数据(我选择 id)并将其发送到后端 /api/folder 我可以在终端中看到对象,但我无法修改它。 你知道为什么吗?谢谢

import db from "@/utils/db";
import Team from '@/modules/Team'


const handler = async (req, res) => {
  
  console.log(req.body)    // { id: '64501115948ae9070cdd5ba5' }

  await db.connect();


  const team = await Team.findById(req.query.id);

  console.log('team', team)
  console.log('name', team.name)
  console.log('game', team.game1)
  
  team.game1 += 1

  await team.save()

  await db.disconnect(); 
  res.status(200).json({ message: 'success '})
};

export default handler

终端输出/team.game1 === undefine 你能告诉我为什么是未定义的以及如何修复它吗? 谢谢


{ id: '64501115948ae9070cdd5ba5' }
use previous connection
teeeeeeeeeeeeeeeeem {
  _id: new ObjectId("64501115948ae9070cdd5ba5"),
  name: 'Boston',
  img: '/bos.png',
  color: '#0800ff',
  updatedAt: 2023-05-02T16:32:57.387Z,
  game1: 5,              // trying modify this one
  game2: 0,
  game3: 0,
  game4: 0,
  game5: 0,
  game6: 0,
  game7: 0
}
name Boston Bruins
game undefined    //   <= here

我不明白,数据在那里,但如果我想选择它,我就会变得不确定。

reactjs mongodb next
1个回答
0
投票

嘿 erza 你能替换你的代码吗-

const handler = async (req, res) => {
  
  console.log(req.body)    // { id: '64501115948ae9070cdd5ba5' }

  await db.connect();


  const team = await Team.findById(req.query.id);

  console.log('team', team)
  console.log('name', team.name)
  console.log('game', team.game1)
  
  team.game1 += 1

  await team.save()

  await db.disconnect(); 
  res.status(200).json({ message: 'success '})
};

用我的代码-

const handler = async (req, res) => {
  
  console.log(req.body)

  await db.connect();


  const team = await Team.findById(req.query.id).lean().exec();

  console.log('team', team)
  console.log('name', team.name)
  console.log('game', team.game1)
  
  team.game1 += 1

  await Team.findByIdAndUpdate(req.query.id, { $set: team }).exec();

  await db.disconnect(); 
  res.status(200).json({ message: 'success '})
};

如果这不起作用只是让我知道我会帮助你更多..

© www.soinside.com 2019 - 2024. All rights reserved.