首页 文章

如何基于引用键检索模式的其他详细信息

提问于
浏览
0

我有一个正在进行的项目 . 我有一个评论架构,喜欢架构和博客架构 . 所有这三个都被声明为单独的模式,但是喜欢和评论模式然后嵌套到博客模式中作为子项,即注释:[CommentSchema] . 现在我有一个页面,当有人点击博客时,它会显示所有评论和博客 . 这个代码获取博客Blog.findById(id).populate('user','username') . exec(function(err,blog) . )现在在comments数组中有一个名为commOwner的键引用objectid从另一个名为user的模式,就像博客模式有一个引用键一样,你可以从代码中看到 . 我试图根据评论模式中的引用键commOwner显示每个人的gravatar和用户名但我不知道如何去做 . 我也希望能够填充那些在博客评论的用户名和gravatar在我为博客做的相同代码中 . 请有人帮我这个 . 下面是我所有模式的代码

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;


/*Comment schema*/
var CommentSchema = new Schema({
    commOwner: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    commbody: {
        type: String,
        default: '',
        trim: true,
        //required: 'Comment cannot be blank'
    },
    updated: {
        type: Date,
        default: Date.now
    }
});

/**
 * Likes Schema
 */
var LikeSchema = new Schema({
    score : {
        type: Number,
        default: 0
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});


/**
 * Blog Schema
 */
var BlogSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    title: {
        type: String,
        default: '',
        trim: true,
        required: 'Title cannot be blank'
    },
    content: {
        type: String,
        default: '',
        trim: true
        //required: 'Content cannot be blank'
    },
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    comments: [CommentSchema],
    likes: [LikeSchema]

});

mongoose.model('Blog', BlogSchema);

1 回答

  • 0
    Blog.findById(id).
      populate(
         [{path:'user', select:'username'},
         {path:'comments.commOwner',select:'username profilepic ...'}])
      .exec(function(err, blog){...})
    

    select 字段中,指定要在 commOwner 中填充的其他字段(以空格分隔) . 看看the docs

相关问题