Mongo子文档人口

时间:2014-06-15 15:59:29

标签: node.js mongodb mongoose documents

您好我有三个型号

帖子:

var PostSchema = new Schema({
title: {
    type: String,
    required: true,
    default: '',
},
content: {
    type: String,
    required: true,
    default: '',
},
community: {
    type: String,
    default: '',
},
price: {
    type: String,
    required: true,
    default: '',
},
location: {
    type: String,
    required: true,
    default: '',
},
images: {
    type:[],
    required: true,
},
user: {
    type: Schema.ObjectId,
    required: true,
    ref: 'User',
},
accepted : {
    type: [],
},
comments: {
    type: [Schema.Types.ObjectId],
    ref:"Comment"
}
});

用户:

var userSchema = mongoose.Schema({

local            : {
    email        : String,       
    password     : String,
},

firstName: { type: String, required: true },
lastName: { type: String, required: true },
location: { type: String, required: true },
profilepicture: { type: String },

});

评论

var CommentSchema = new Schema({
title: {
    type: String,
    default: '',
},
content: {
    type: String,
    default: '',
},
user: { 
    type: Schema.ObjectId, 
    ref: 'User' 
},
post: {
    type: Schema.ObjectId,
    ref: 'Post'
},
offer: {
    type: String,
    default: '',
}
});

我正在尝试允许Posts模型具有一个对象id的注释数组,并且注释要在那里填充用户objectid。我使用下面的代码作为我的帖子路线,我可以得到所有的评论填充,但我不能让评论的用户填充。理论上这应该根据mongo文档工作,但它不是。有什么想法吗?

app.get('/api/posts', function(req, res) {

Post.find().populate('user comments comments.user').exec(function(err, posts) {
    if (err) {
        res.render('error', {
            status: 500
        });
    } else {
        res.jsonp(posts);
    }
});
});

1 个答案:

答案 0 :(得分:1)

要做你想做的事,你需要在初始填充调用完成后调用内部“comments”对象上的populate。在您的商家信息的简化版中:

var async = require("async"),
    mongoose = require("mongoose"),
    Schema = mongoose.Schema;

mongoose.connect("mongodb://localhost/user");

var postSchema = new Schema({
  title: { type: String, required: true, default: '' },
  user: { type: Schema.Types.ObjectId, required: true, ref: 'User' },
  comments: [{ type: Schema.Types.ObjectId, ref: "Comment" }]
});

var userSchema = new Schema({
  name: String
});

var commentSchema = new Schema({
  content: String,
  user: { type: Schema.Types.ObjectId, ref: "User" },
  post: { type: Schema.Types.ObjectId, ref: "Post" }
});

var Post = mongoose.model( "Post", postSchema );
var User = mongoose.model( "User", userSchema );
var Comment = mongoose.model( "Comment", commentSchema );

在评论中填充“用户”将是这样的:

Post.find().populate("user comments").exec(function(err,docs) {

    async.forEach(docs,function(doc,callback) {
      Comment.populate( doc.comments,{ "path": "user" },function(err,output) {
        //console.log( "doc: " + doc );
        //console.log( "proc: " + output );
        callback();
      });

    },function(err) {
      console.log( "all: " + JSON.stringify(docs,undefined,4 ));
    });

});

或者您实际上正在处理帖子中的查找结果。关键是您的“注释”需要先填充,然后您可以使用模型表单在结果中的每个文档的整个“注释”数组中调用.populate()