When I get a POST request, I want to get the entries whose keys are present in my model's schema. For example, if my 'user' model's schema consists of 'name' and 'email' keys, then as I iterate over req.body, I only want to get values for the 'name' and 'email' fields. How do I do that?
if you have form fields like,
<input type="text" name="name">
<input type="text" name="email">
then instead of iterating over req.body, you can,
var name = req.body.name;
var email = req.body.email;
Here's some code that retrieves fields from the body of a post request, using express with the bodyParser() middleware :
var express = require('express');
var app = express();
// Middleware
app.use(express.bodyParser());
... // other middleware
// Routes
app.post('/path', function(req, res) {
var name = req.body.user.name;
var email = req.body.user.email;
... // some more code
});
Hope that helps.
If I understand your question correctly, you are wanting to have an unspecified set of keys to query mongo with, and to only return data for those keys.
If that is in fact the case, using Mongoose with lodash/underscore:
var keys = _.keys(req.body);
User.find(req.body).select(keys.join(' ')).lean().exec(function(err, user {
if (err)
throw err;
res.send(user);
}):
That's assuming certain things about the req.body object and how keys match up to the schema.