gpt4 book ai didi

node.js - Mongodb子文档填充

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:39 26 4
gpt4 key购买 nike

您好,我有三个模型

帖子:

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: '',
}
});

我试图允许帖子模型拥有评论的对象 ID 数组,并让评论填充用户对象 ID。我在我的帖子路由中使用下面的代码,我可以填充所有评论,但无法填充评论的用户。理论上,这应该根据 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);
}
});
});

最佳答案

要执行您想要的操作,您需要在初始填充调用完成后对内部“评论”对象调用填充。在您的列表的简化版本中:

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() ,使用模型形式,对结果中每个文档的整个“评论”数组进行分析。

关于node.js - Mongodb子文档填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com