Reputation: 613
Suppose I have a very simple Schema like this:
const PlayerSchema = new Schema({
Region: {type: String},
Tier: {type: String},
Division: {type: String}
});
And further suppose that PlayerSchema lives in a MongoDB collection, where making a GET request to "/players" return a list of all the players in the collection:
router.get("/players", function(req, res){
DbSchemas.PlayerSchema.find({}).then(function(players){
res.send(players);
});
});
This is the response I get from making that GET request to "/players":
[
{
"Region": "North America",
"Tier": "Gold",
"Division": "III"
},
{
"Region": "Asia",
"Tier": "Platnium",
"Division": "IV"
}
]
However, suppose now I want to add some custom data to the PlayerSchema that are not in the database. I want the result returned to be something like this:
[
"code": 200,
"status": "OK",
"data": {
{
"Region": "North America",
"Tier": "Gold",
"Division": "III"
},
{
"Region": "Asia",
"Tier": "Platnium",
"Division": "IV"
}
]
Basically, I still want the MongoDB collection to store only the PlayerSchema (without the code and status), I would like to append the code:200 and status:OK myself if possible.
Here's what I tried. It doesn't work. I start by creating another schema:
const PlayerDataSchema = new Schema({
code: {type: Number},
status: {type: String},
data: {
type: [PlayerSchema]
}
});
Then, I tried to create an instance of PlayerDataSchema using the constructor, and assigning the PlayerSchema object to PlayerDataSchema.
router.get("/players", function(req, res){
DbSchemas.PlayerSchema.find({}).then(function(players){
var PlayerData = new DbSchemas.PlayerDataSchema({ ResponseCode:200 }, { ResponseStatus:"OK" }, {Players: players});
res.send(PlayerData);
});
});
This doesn't work and just gives me a TypeError: DBSchemas.PlayerDataSchema is not a constructor.
How do I add custom data into a schema?
Upvotes: 1
Views: 640
Reputation: 4704
You don't need to modify the schema to add fields to the response.
Your desired output isn't valid json:
[
"code": 200,
"status": "OK",
"data": {
{
"Region": "North America",
"Tier": "Gold",
"Division": "III"
},
{
"Region": "Asia",
"Tier": "Platnium",
"Division": "IV"
}
]
Arrays contain objects, and you're putting key-pairs in. That won't work.
That said, you just need to take the response and manipulate it with javascript to make it whatever you need it to be.
For example, if your retrieved data is this array:
players = [
{
"Region": "North America",
"Tier": "Gold",
"Division": "III"
},
{
"Region": "Asia",
"Tier": "Platnium",
"Division": "IV"
}
]
You can make another object to return like this:
result = {
code: 200,
status: "OK",
data: players
};
So your return value would be:
{
code: 200,
status: "OK",
data: [
{
"Region": "North America",
"Tier": "Gold",
"Division": "III"
},
{
"Region": "Asia",
"Tier": "Platnium",
"Division": "IV"
}
]
};
Which is an object with 3 keys, a number, a string, and an array.
I hope that sets you on the right course.
Upvotes: 1