Wednesday, 19 April 2017

'null' Passed Into Mongoose Query 'findOne()'

I am running into an issue I cannot seem to resolve for the past few hours. Let's get to it.

Currently using the most recent version of express and mongoose

I have the following route with the query in my route.js:

Note
    .findOne({"user": req.params.user, "title": req.body.title, "subtitle": 
     req.body.subtitle})
    .exec(function (err, note) {
       if (err) {handleError(err)};
       console.log(note._id);
    })
    //same implementation as the in the mongoose docs

Then, I have a client side script with the following ajax request:

let settings = {
        type: 'GET',
        url: 'http://localhost:8080/note',
        data: {
            "user": userId,
            "title": noteTitle,
            "subtitle": noteSubtitle
        },
        dataType: "json",
        success: renderGetNoteTemplate
    }
    return $.ajax(settings);

Now the problem is that, even when a document does exist in the database and right collection, the query result is null. And after hours of reading threads on this site and also logging to the console, I decided to log the query to the console and saw this!

_conditions: { subtitle: null, title: null, user: null }

So the condition being passed is null, which obviously will return null. Now, here is the catch. The queries work with conditions such as:

Note.findById(req.cookies.note).exec()

The difference that I could see there is, that the request is not coming from the body. So above I sent the conditions in via the ajax request with something like

{"title": req.body.title}

Lastly, when I just print the req.body.title, etc to the console without passing it to the query, the values come up. So for example, I pass in Romeo And Juliet as the noteTitle, when I print it on the server console, I get the value Romeo And Juliet. It's as soon as I pass it into the query as a condition that the problem arises.

Have literally looked everywhere, especially the way I named my models, etc. Again when I pass req.body argument into the condition then I get the null result.

Also for the sake of brevity, I did not include in the code that I have required bodyParser and so again, the values do show up when it is not going into the query condition.

Any ideas what makes these arguments become null?

Thanks



via Bry

No comments:

Post a Comment