简体   繁体   中英

cant update in mongoDb with mongoose

I am trying to create a followers/following function in my project. However I cannot seem to update the DB correctly. I'm able to send the ids as they both print when I console.log but nothing in my DB updates and I do not get any response in my frontend.

route

app.put('/api/follow', async function (req, res, next){
    const { id } = req.query;
    const userFrom = req.body.data

    console.log('OTHER USER ID',id)
    console.log('CURRENT ID', userFrom)

    User.findByIdAndUpdate(id), {
      $push:{followers:req.body.data}
    },{new:true},
  (err,result)=>{
    if(err) {
      if(err) return res.status(400).send(err)
    }
    User.findByIdAndUpdate(req.body.data), {
      $push:{following:id}
    },{new:true}.then(result=> {
      res.json(result)
    }).catch(err=>{
      return res.status(422).json({error:err})
    })   
  }
  })

user model

const mongoose = require("mongoose");

const User = mongoose.model(

      "User",
      new mongoose.Schema({
        username: String,
        email: String,
        password: String,
        phoneNo: String,
        bio: String,
        filePath: String,
        following: [
          {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
          },
        ],
        followers: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User",
        },
      })
    );
    
    module.exports = User;

my route end function

const clickHandler = () => {
        
        const currentID = currentUser.id;
        const id = this.props.id;
        
        console.log('CURRENT ID',currentID)
        console.log('otherUserID',id)
    
        Axios.put(`http://localhost:8080/api/follow/?id=${id}`,  { data: currentID }, { headers: authHeader() })
        .then(response => {
            if (response.data.success) {
                console.log('FOLLOWED', response.data)
                // this.setState({ userDetails: response.data.details })
            } else {
                alert('Error')
            }
        })
    }

This should be User.findByIdAndUpdate(id, {

You should not close the bracket after id but after new: true})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM