如何在填充之后在猫鼬中放松

时间:2014-08-25 19:24:20

标签: mongodb mongoose populate

我有两个模式,邮件和用户,如下所示:

var MailsSchema = new Schema({
    from   : [{ type: ObjectId, ref: 'UsersSchema' }],
    to   : [{ type: ObjectId, ref: 'UsersSchema' }],
    date    : { type: Date, default: Date.now },
    subject : { type: String, default: '' },
    message : { type: String, default: '' },
    isRead  : { type: Boolean, default: false }
});

var UsersSchema = new Schema({
    username    : String,
    pass : String,
    firstName : String,
    lastName  : String,
    age :   Number
});

我想获取发送给特定用户的邮件列表,在'from'字段中填充用户名,

我试着这样做:

mails.find({ to: id }).populate('from', 'username').exec(function (err, docs)...

问题是: 我在'from'字段中得到一个数组,我想只得到用户名。

即。而不是得到这个结果:

[{"_id":"53fa2902da480e4c0d315fcd","__v":0,"isRead":false,"message":"SABABA","subject":"MA KORE","date":"2014-08-24T18:03:46.428Z","to":["53f9dbe164b1375c1c5b997a"],"from":[{"_id":"53f9dbe164b1375c1c5b997a","username":"adaroh"}]}]

我想得到那个结果:

[{"_id":"53fa2902da480e4c0d315fcd","__v":0,"isRead":false,"message":"SABABA","subject":"MA KORE","date":"2014-08-24T18:03:46.428Z","to":["53f9dbe164b1375c1c5b997a"],"from":"adaroh"}]

1 个答案:

答案 0 :(得分:0)

这就是人们的生活方式。您可以自己修改文档以过滤掉额外的ID。在exec中,对于每个填充的文档,您可以查看from数组并执行

doc.from[i] = doc.from[i].username