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

1 回答 1

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

select字段中指定要填充的其他字段(以空格分隔)commOwner。看看文档

于 2014-08-04T15:29:28.573 回答