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.

1 Answer 1

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);
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

@user3211705 No worries, happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.