0

I want to select a whole document and send it as JSONObject.

app.post('/getinvbykost', function(request, response){ 
    var tablename = request.body.tablename; 
    Move.find({tablename: tablename}, function(err, doc) {
        response.json(doc);
    }); 
});

This gives the correct result but with "[]" ->Array and not with {} ->JSONObject. btw: I got the same issue with Move.aggregate(pipeline, function(err, res) {...

result:

[
  {
    STUFF  
  }
]

There is a function $unwind but I dont get it....

4
  • So.... respond with just the first one. doc[0] Or, use the findOne method. Commented Jul 23, 2015 at 19:35
  • 1
    Please note, there's no such thing as a JSONArray or a JSONObject, only JSON, Objects, and Arrays. doc is an array, and express converts it to JSON when sending it to the client using the res.json method. Commented Jul 23, 2015 at 19:36
  • Well, that's because #find returns an array of documents. If you need your results to be an Object with each property corresponding to some identifying data, use _.indexBy or similar code of your own. Commented Jul 23, 2015 at 19:37
  • findOne solved it, so easy ;) thanks Commented Jul 23, 2015 at 19:38

1 Answer 1

1

In this case since you only want one result, the findOne method would be more appropriate.

app.post('/getinvbykost', function(request, response){ 
    var tablename = request.body.tablename; 
    Move.findOne({tablename: tablename}, function(err, doc) {
        response.json(doc);
    }); 
});
Sign up to request clarification or add additional context in comments.

8 Comments

Yes, that was my comment. :)
I need to put a WHERE clause in it. It is right that findOne doesnt accept a WHERE-clause?
the tablename: tablename is a where clause. but, yes, you can remove the callback and instead use .where and .exec
blind in the morning, of course, thank you Model.findOne({tablename: tablename, accepted : false}, function(err, res) {}
The result is a JSONObject. Why i cant push another value to it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.