【问题标题】:how to unwind in moongose after populate填充后如何在猫鼬中放松
【发布时间】:2014-08-28 02:06:34
【问题描述】:

我有两个架构,邮件和用户,定义如下:

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
});

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

我试图这样做:

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"}]

【问题讨论】:

    标签: mongodb mongoose populate


    【解决方案1】:

    这就是填充的工作原理。您可以自己修改文档以过滤掉额外的 id。在您的exec 中,对于每个填充的文档,您可以查看from 数组并执行

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-26
      • 2016-06-11
      • 2017-01-23
      • 2015-09-30
      • 2012-11-11
      • 2016-12-19
      • 2015-07-13
      • 2016-10-10
      相关资源
      最近更新 更多