
API Design in Node.js, v3 Read Many Documents Solution
This course has been updated! We now recommend you take the API Design in Node.js, v4 course.
Transcript from the "Read Many Documents Solution" Lesson
[00:00:00]
>> Scott Moss: So for getMany, I don't know, if we look at the test, it says, finds an array of docs by an authenticated user. Okay, so what we can do is, we'll just say, docs = await. And we know getMany we can do model.find. And we wanna get it by the user, which will be createdBy, And the user, excuse me, is gonna be on req.user.id.
[00:00:30]
>> Scott Moss: And then we'll say .exec.
>> Scott Moss: And then we'll say res.status(200).json([data: docs}.
>> Scott Moss: And the reason I put data here is like cuz that's what the test is looking for. [LAUGH] But no, it's a really good idea to like namespace your responses from the server with some field on them, so your client knows that the data's always gonna be on this field.
[00:01:03] Cuz if you just send back just the raw thing like this, like for instance, docs. It's not socs. [LAUGH] Docs. Okay, if I send back docs like this, that's an array. And then up here I sent back doc, that's an object. Those are two different types of data structures.
[00:01:19] And now the front end's gotta check to see which one's which. So it's better just to always send back the right, to send back a namespace. Always like to name place it with data. So always send an object that has data, and then the result of the operation that you want is always on the data property.
[00:01:35] And this allows you to do other things too. If you wanted to also send back detailed error messages, you could say errors. And if you have no list of detailed error messages that you can display on the screen for some other reason. So it's just namespacing like the result of the information that you asked for, versus just throwing the whole result of the database as the root object.
[00:01:53] You kinda lose out on a lot of free stuff there. So just pick a namespace. I use data cuz that's what Graph Field does, and I use Graph Field a lot, so that's why I use that. Okay, so now if we run the test
>> Scott Moss: We're gonna see if this passed, which it looks like it did.
[00:02:12] So cool, finds array of documents by authenticated user. Got that.