【问题标题】:how to retrieve other details of a schema based on the reference key如何根据引用键检索架构的其他详细信息
【发布时间】:2014-09-25 13:25:24
【问题描述】:

我有一个项目正在进行中。我有一个评论模式、一个喜欢模式和一个博客模式。这三个都被声明为单独的模式,但喜欢和 cmets 模式随后作为子模式嵌套到博客模式中,即 cmets: [CommentSchema]。现在我有一个页面,当有人点击博客时,它会显示所有 cmets 以及博客。这是获取博客 Blog.findById(id).populate('user', 'username').exec(function(err, blog) 的代码。现在在 cmets 数组中有一个名为 commOwner 的键,它引用 objectid从另一个名为 user 的模式中,就像博客模式也有一个引用键,正如您从代码中看到的那样。我试图显示每个根据 cmets 模式中的引用键 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);

【问题讨论】:

    标签: mongodb express mongoose mongoose-populate


    【解决方案1】:
    Blog.findById(id).
      populate(
         [{path:'user', select:'username'},
         {path:'comments.commOwner',select:'username profilepic ...'}])
      .exec(function(err, blog){...})
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多