0

I've recently started using the MEAN stack and stumbled upon some errors while trying to work with my MongoDB database. I connected to the database successfully, implemented my CRUD routes, and I get wrong values for anything besides the find() method (which returns all the documents in my collection without any problem). The findOne() looks like this for example:

router.route(server.get("/company/:id", (request, response) => {
        const companyId = request.params.id;
        console.log("Showing company with id: " + companyId)

        dbCollection.findOne({ _id: mongodb.ObjectId(companyId) }, (error, result) => {
            if (error) throw error;
            // return company
            response.json(result);
        });
    }));

The result after making a get request via Postman is null

The insertOne() looks like this:

router.route(server.post("/company/add", (request, response) => {
        const company = request.body;
        dbCollection.insertOne(company, (error, result) => { 
            if (error) throw error;
            // return updated list
            dbCollection.find().toArray((_error, _result) => { 
                if (_error) throw _error;
                response.json(_result);
            });
        });
    }));

It adds one document to the database with the ID that it creates for itself, but for some reason it doesn't take in the body data (2 string elements { "name": "xy", "type": "company" })

And last but not least, the deleteOne():

router.route(server.delete("/company/delete/:id", (req, res) => {
        const companyId = req.param.id;
        console.log("Delete company with id: ", companyId);

        dbCollection.deleteOne({ _id: mongodb.ObjectId(companyId) }, function(err, result) {
            if (err) throw err;
            // send back entire updated list after successful request   (optional)
            dbCollection.find().toArray(function(_err, _result) {
                if (_err) throw _err;
                res.json(_result);
            });
        });
    }));

For some reason it deletes the very first document in the collection, but not the one that is entered with the corresponding ID.

If anyone could help me out with this it would be awesome. Thank you in advance!

Edit 1: Adding a new document to the collection via Postman

Collection after the add

Edit 2: Get request via ID and response (returns null)

Console output: Showing company with id: 5e63db861dd0ce2418ce423d

Edit 3:

Corrected the code for the findOne() and deleteOne() methods.

When you try with _id you need to convert the string(request.params.id) to ObjectId().
Convert string to ObjectID in MongoDB - whoami

CodingIsFun
  • 1
  • 1
  • 4
  • Can you edit this question with request being passed to `/add` & document saved in DB !! Do you've `id` field in request & MongoDB doc ? – whoami - fakeFaceTrueSoul Mar 07 '20 at 18:54
  • Added 2 screenshots as further info. I'm letting mongoDB add the objectId by default, so I'm only passing in the 2 string elements as a json. – CodingIsFun Mar 07 '20 at 19:11
  • Then you need to query on field `_id` but not on `id`, what is this `{ id: companyId }` ? What are you getting here `request.params.id`, can you print it & give it to us ? In your collection I can see certain docs with 3 fields but last one has only `_id` is that inserted thru code & remaining else were manually done ? – whoami - fakeFaceTrueSoul Mar 07 '20 at 19:13
  • Yes, the first 3 docs that have 3 fields (_id, name, type) have been entered manually, the last one (only 1 field "_id") was added via the post request. I tried to query both on `id` and `_id`, the results are the same. – CodingIsFun Mar 07 '20 at 19:25
  • When you try with `_id` you need to convert the string(request.params.id) to `ObjectId()`, Are you using `mongoDB-driver` or `mongoose` ? Check this :: https://stackoverflow.com/questions/7825700/convert-string-to-objectid-in-mongodb – whoami - fakeFaceTrueSoul Mar 07 '20 at 19:26
  • I'm using `mongoDB-Driver` . Using `_id` and converting the `request.params.id` to `ObjectId()` helped, now the `findOne()` and `deleteOne()` work just as expected, thank you! The only thing that is still acting up is the post request ( /add), that only adds a new document with the id, but not the other parameters that are sent via the request body. Do I also have to specify the parameters in the query, so instead of `const company = request.body;` `dbCollection.insertOne(company, ...)` something like `dbCollection.insertOne( { name: req.body.name, type: req.body.type }` ? – CodingIsFun Mar 07 '20 at 20:26
  • Did you try to do `const company = JSON.parse(request.body)`, It will convert request string to request JSON object.. – whoami - fakeFaceTrueSoul Mar 07 '20 at 20:52
  • I tried using `const company = JSON.parse(request.body)`, I get a syntax error saying: `SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at x/server.js:59:30 at Layer.handle [as handle_request] at next at Route.dispatch at Layer.handle [as handle_request] at at Function.process_params at next at jsonParser` I also tried doing with `.insertOne( { name; request.body.name, type: req.body.type }, ...) ` which inserts a document with the 3 parameters, but takes _null_ as the name and type parameter – CodingIsFun Mar 07 '20 at 22:27
  • What do you’ve in request.body ? – whoami - fakeFaceTrueSoul Mar 07 '20 at 22:28
  • Just checked it, it returns an empty array named _company_, so instead of `name: "xy", type: "company" ` I get a `company: {}` – CodingIsFun Mar 07 '20 at 22:32
  • So far I was able to get rid of the `company: {}` and make sure it inserts a document with _name_ and _type_ (doing so with `insertOne( { "name": company.name, "type": company.type }` ) but they get inserted with the values _null_ instead of the actual request body. – CodingIsFun Mar 07 '20 at 23:24
  • Use json parse and use tequest.body directly in insertOne – whoami - fakeFaceTrueSoul Mar 07 '20 at 23:27
  • Using `JSON.parse()` isn't necessary, since the `request.body` is already in json format (that's why I got the SyntaxError: unexpected token o in JSON... before, just did some research on that). Also if I use the request.body directly in `insertOne()`, the inserted document only contains the `_id` and not the _name_ or _type_ . – CodingIsFun Mar 07 '20 at 23:38

0 Answers0