Sarah
Sarah

Reputation: 81

Unable to update MongoDB collection by matching _id

First, I Registered a user using His email and password.

Now if

I try to Update or Make user details by matching the Id assigned by the Mongo Database while registering the user.

it's not accepting it.

error is like this

Parameter "filter" to find() must be an object, got 60b10821af9b63424cf427e8

if I parse it like

Model.find(parseInt(req.params.id))

it shows a different error.

Well here's the Post Request

//Post request to create user details by matching Id.
// Id I am trying to match is the id that was given by the database


app.post("/user/:id", async(req, res) => {
    console.log("not found");

    if (await Model.find(req.params.id)) {
        const users = new Model({
            fName: req.body.fName,
            sName: req.body.sName,
            birth: req.body.birth,
            phone: req.body.phone,
            SSN: req.body.SSN
        });
        const result = await users.save();
        console.log(result);
        return res.send({
            "Success": true,
        });
    } else {
        console.log(req.params.id);
        res.status(404).send({ "message": false });
    }
});

Here's the schema

const LoginSchema = new mongoose.Schema({
    email: { type: String, required: true },
    password: { type: String, required: false },
    otp: String,
    token: String,
    fName: String,
    sName: String,
    birth: Number,
    phone: Number,
    SSN: Number

});

Here are the headers I used

const express = require("express");
const app = express();
const mongoose = require("mongoose");
app.use(express.json());
app.use(express.urlencoded({ extend: true }));


Database id assigned which I use

{
  _id: 60b1131271129a3cf8275160,
  email: '[email protected]',
  password: '$2b$10$FWAHu4lP9vn14zS/tWPHUuQJlO7mjAUTlPj.FliFAZmCNA23JA3Ky',
  __v: 0
}

Upvotes: 0

Views: 615

Answers (2)

Đăng Khoa Đinh
Đăng Khoa Đinh

Reputation: 5411

The error:

Parameter "filter" to find() must be an object, got 60b10821af9b63424cf427e8

means: You need to provide an object as the argument of the find() method, not a string ("60b10821af9b63424cf427e8" in this case). Moreover, find() will give you an array, if you find an item in the database, use findOne() instead.

Change from :

await Model.find(req.params.id)

to :

await Model.findOne({_id : req.params.id})

Another way is to use findById() method like this : await Model.findById(req.params.id)

Upvotes: 1

Fad
Fad

Reputation: 9858

Likely the error is caused by the fact that you're passing a string from the request when Mongoose is expecting an instance of mongoose.Types.ObjectId. You should be able to fix the problem by casting the string into said type.

await Model.find(mongoose.Types.ObjectId(req.params.id))

Upvotes: 1

Related Questions