Is there a way to only return fields defined within a Mongoose schema?
no need to define another schema to get specific property from a collection. Just specify which properties you want to return in find()
function as projection option.
Schema.find(query,options,callbackFunction);
like:
person.find({},{name:1}, function(err, docs) {//used name:1 to return only name if(error) { return res.status(400).send({msg: "error"}); } return res.status(200).send(docs);});
I have an idea of using "select: false" on the Reference schema. We still have to list/define all the related fields.
For example,
{ "name": "John", "age": 25, "gender": "male"}
var Person = mongoose.Schema({ "name": String, "age": Number, "gender": String}, {collection: "People");var PersonRef = mongoose.Schema({ "name": String, "age": { type: Number, select: false }, "gender": { type: String, select: false },} {collection: "People"});
But this method will only applicable (or useful) when the schema is relatively small for maintainability. If the schema grown bigger, then we will need to set select: false
in both (or multiple schema) to avoid auto select in RefSchema.
I'm still looking for a better solution to handle this.