1

I have a Model structure as below in which the stage is retrieved from another model

var stageSchema = new Schema({
  Name: String,
  Stage: {
    type: Schema.ObjectId,
    ref: 'StageName',
  }
}, {
  collection: 'StageList'
});

I have written query to retrieve data using mongoose as shown below:

exports.findall = function(req, res) {
    stage.find().populate({path:'Stage',select:'-_id'}).lean().exec(function(err, value1) {
        res.send(value1);
  });
};

It displays the result as shown below

[{_id:213465465465465, Name: "AAA", Stage: {Value: "Stage1"}},{_id:213465465465465, Name: "BBB", Stage: {Value: "Stage2"}}]

But I want the Stage to be in array format without the key "Value" as shown below:

[{_id:213465465465465, Name: "AAA", Stage: ["Stage1"]},{_id:213465465465465, Name: "BBB", Stage: ["Stage2"]}]

Please help to get through this problem. Thanks in advance.

user3211705
  • 2,418
  • 3
  • 19
  • 36

1 Answers1

2

To modify the resulting document for Stage to be in array format without the key "Value", use JavaScript's map() method to create a new array in which you modify the objects within the array as follows:

exports.findall = function(req, res) {
    stage.find().populate({path: 'Stage', select: '-_id'}).lean().exec(function(err, results) {
        var value1 = results.map(function (r){
            var stageVal = r.Stage.Value;
            r.Stage = [stageVal];
            return r;
        });
        res.send(value1);
    });
};
chridam
  • 100,957
  • 23
  • 236
  • 235