如何以mongoose的数组格式填充数值
我有一个模型结构如下,其中舞台从另一个模型中检索
var stageSchema = new Schema({ Name: String, Stage: { type: Schema.ObjectId, ref: 'StageName', } }, { collection: 'StageList' });
我写了查询来检索使用mongoose的数据,如下所示:
exports.findall = function(req, res) { stage.find().populate({path:'Stage',select:'-_id'}).lean().exec(function(err, value1) { res.send(value1); }); };
它显示如下所示的结果
[{_id:213465465465465, Name: "AAA", Stage: {Value: "Stage1"}},{_id:213465465465465, Name: "BBB", Stage: {Value: "Stage2"}}]
但是我希望舞台是没有“价值”键的数组格式,如下所示:
[{_id:213465465465465, Name: "AAA", Stage: ["Stage1"]},{_id:213465465465465, Name: "BBB", Stage: ["Stage2"]}]
请帮助解决这个问题。 提前致谢。
要将Stage生成的文档修改为数组格式,而不使用“Value”键,可以使用JavaScript的map()
方法创build一个新数组,在其中修改数组中的对象,如下所示:
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); }); };