【问题标题】:mongoose - set presentation of foreign key referencemongoose - 设置外键引用的表示
【发布时间】:2016-08-06 03:01:08
【问题描述】:

我正在为移动应用开发一个 REST API,这是我正在使用的模型的一部分

var UserSchema = new Schema(
{
    email : 
    {
        type : String, 
        unique : true
    },
    login_type : String,
    username : 
    {
        type : String,
        index : true
    },
    password : String
}

我添加了用户的 oid 来发布架构作为参考

var PostSchema = new Schema(
{
    author : {type : Schema.Types.ObjectId, ref : "User"},
    board_id : {type : Schema.Types.ObjectId, ref : "Board"},
    regDate : Number,
    lastModDate : Number,
    title : String,
    content : String,
}

因此,帖子可以引用用户收藏以获取发布它的用户的username。所以我只想得到用户的用户名,其他人不是必需的。 为此,我使用了以下。

var query = Post.find({"regDate" :{$lte : before}},
{
    _id : 1,
    title : 1,
    "author.username" : 1,
    regDate : 1
})

但是猫鼬忽略了"author.username"。我怎样才能只获得author 的用户名,而不是全部?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您应该使用populate 函数并在那里枚举选定的字段:

    Post
        .find({ regDate :{ $lte : before }}, 'title reqDate')
        .populate('author', 'username')
        .exec();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2013-05-26
      • 2021-01-21
      • 1970-01-01
      相关资源
      最近更新 更多