Hanson Hanson - 2 months ago 8
Node.js Question

Firebase Saving Object as Key to Database

router.post('/postChef', function(req, res, next) {
var userid = req.body.userID;
var mealid = req.body.mealID;
db.ref("chefs/" + userid).child("Meals").set({
mealid : true
});
res.send('respond with a resource');
});


In the code above, I'm not sure why mealid gets changed into a "mealid" in the firebase database. What I want is the string value of mealid given by the function. How can I do this? In the defined path, Meals is a child containing a JSON list of all the mealIDs set to true or false.

Answer

Since you use the term "mealid" on the left-hand side of a property assigned, it is interpreted as a string and not as a variable.

To use the value of mealid as the name of the property, switch to "square bracket" notation:

router.post('/postChef', function(req, res, next) {
    var userid = req.body.userID;
    var mealid = req.body.mealID;
    var obj = {};
    obj[mealid] = true;
    db.ref("chefs/" + userid).child("Meals").set(obj);
    res.send('respond with a resource');
});
Comments