Upsert document in mongoose using updateOne where filter and update are the same

Viewed 24

I want to search the collection at each page refresh to check if a user with this address exists, otherwise create a new document with this address. I'm using mongoose in a nextJs application. The Filter and Update value are the same.

It actually does create a new document if there is none that matches the filter but I'm still getting a 400 (Bad Request) Error. How do I fix the error and is this even the right way to do this?

const [state, setState] = React.useState<{
        address?: string
        error?: Error
        loading?: boolean
      }>({})

const userData = { address: state.address }

const createUser = async () => {
    try{
      const res = await fetch("/api/users",{
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData),
      })
    } catch (error) {
     console.log(error);
    }
}

React.useEffect(() => {

  createUser()

}, [])

model:

import mongoose from 'mongoose'

const UserSchema = new mongoose.Schema({
    address: {
        type: String,
        unique: true
    },
})

export default mongoose.models.User || mongoose.model('User', UserSchema)

api/users/index

import dbConnect from '../../../lib/dbConnect';
import User from '../../../models/User';

export default async function handler(req, res) {
  const { method } = req
   
  await dbConnect()
  
  .
  .
  .


  case 'PUT':
      try{
        const updateUser = await User.updateOne(
          req.body,
          req.body,
          {new:true, upsert:true })
        res.status(200).json({ success: true, data: updateUser})
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break
 
  
   .
   .
   .
}

0 Answers
Related