您好我有三种型号
帖子:
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);
}
});
});
要执行您想要的操作,您需要在初始填充调用完成后在内部“ comments”对象上调用填充。在清单的简化版本中:
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()
使用模型表单在结果中每个文档的整个“注释”数组上调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句