skip to Main Content

I have data in mongo. I fetch this data from mongo to screen. Then I want update data, by onClick (I select id) and send it to backend /api/folder
I can see object in terminal, BUT I cannot modify it.
Do you know why? Thanks

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

terminal output / team.game1 === undefine
can you please tell me why is undefine and how to fix it?
thanks


{ 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

I dont understand it, data are there, BUT if I want to select it I am getting undefined.

2

Answers


  1. Chosen as BEST ANSWER

    Finally, I got it, I change my mind and set new data in mongo database, BUT I DID NOT CHANGE MODULESCHEMA in pc. I saw data in database but could not change it because of module wasn't change! I will remember it!!!!


  2. Hey erza could you please replace your code-

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

    with my code-

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

    if this doesn’t work just lemme know ii will help you more..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search