Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

After inserting data on mongodb it shows me Cannot read property '_id' of undefined in node js ?

By M.K. Verma · 2 May 2022

After inserting data on mongodb it shows me Cannot read property '_id' of undefined in node js ?

you can use save method instead of insertOne first instantiate your object by adding new databaseCollection(newService). and after that call save method to insert your collection

Use res.json instead of res.send to enforce Content-Type to be of JSON type

Your code should look like this:

app.post("/service", async (res, req) => {
    const newService = req.body;
    try {
        const service= await new databaseCollection(newService);
        const savedService=await service.save()
        res.status(200).json(savedService);
    } catch (err) {
        res.status(500).json(err);
    }
});