I am using the mongo db 'ref' functionality to populate objects from a table into a document that I am returning
Here is the table that stores the object ID ref
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const StaticAssignmentSchema = new Schema({
affiliation: { type: String },
REF_person: [{ type: Schema.Types.ObjectId, ref: 'users' }],
});
module.exports = StaticAssignmentNew = mongoose.model('staticassignments', StaticAssignmentSchema);
Here is my users table schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: { type: String },
phone: { type: String },
password: { type: String },
affiliation: { type: String },
timezone: { type: String },
date: { type: Date, default: Date.now },
});
module.exports = User = mongoose.model('users', UserSchema);
Here is how I am getting the data from mongo
var query = { affiliation: affiliation };
var ret = await StaticAssignment.findOne(query).populate('REF_person');
which returns the following:
{
"_id": "61a8376154377e5704ae79cf",
"affiliation": "800_800",
"REF_person": [{
"_id": "5e441bd5332359211c0403fb",
"name": "Frank",
"phone": "8008008001",
"password": "$2a$10$T9wYLE3v/n8S4GB.oyYOmCsGUdxXQiOjpiDaG0JGbKy",
"affiliation": "800_800",
"timezone": "America/Los_Angeles",
"date": "2020-02-12T15:37:57.167Z"
}]
}
however, I would like to return a subset of the populate call:
{
"_id": "61a8376154377e5704ae79cf",
"affiliation": "800_800",
"REF_person": [{
"_id": "5e441bd5332359211c0403fb",
"name": "Frank",
"phone": "8008008001",
}]
}
what can I do to return the subset ?
thank you Mastermind !
ANSWER:
var query = { affiliation: affiliation };
var ret = await StaticAssignment.findOne(query)
.populate({path: 'REF_person', select: '_id name phone'});
CodePudding user response:
Try var ret = await StaticAssignment.findOne(query).populate({path: 'REF_person', select: 'name phone'});
Check out this page: https://www.codegrepper.com/code-examples/whatever/mongoose populate select fields