i'm trying limit fields user can post when inserting object in mongodb. know ho can enforce fields filled can't seem find how people inserting fields don't want.
this code have inserting item.
app.post("/obj", function (req, res) { var newobj = req.body; //todo filter fields don't want ? if (!(newobj .id || newobj .type)) { handleerror(res, "invalid input", "must provide id , type.", 400); return; } db.collection(obj_collection).insertone(newobj, function(err, doc) { if (err) { handleerror(res, err.message, "failed create new object."); } else { res.status(201).json(doc.ops[0]); } }); });
there's js native ways this, tend use lodash toolbox projects, , in case setup whitelist of allowed fields, , extract posted values so:
const _ = require('lodash'); app.post("/obj", function (req, res) { var newobj = _.pick(req.body, ['id', 'type','allowedfield1','allowedfield2']);
this pretty straightforward, , define whitelist somewhere else reuse (e.g. on model or like).
as side note, avoid using 'id' field can post new objects, unless need to, avoid confusion autogenerated _id field.
also, should mongoose rather using straight mongodb driver, if want have more model-based control of documents. among other things, strip fields off object if they're not defined in schema. still use _.pick()
method when there things are defined in schema, don't want people change in particular controller method.
Comments
Post a Comment