Filter by userId



我需要通过userId过滤帖子列表和评论列表。我传递userId参数作为postCreator和commentCreator。我做错了什么?

//data type for comments 
const commentSchema = new mongoose.Schema(
{comment: {
type: String,
required: [true, "comment can not be empty"],
},
createdAt: {
type: Date,
default: Date.now(),
},
vote: {
type: Number,
default: 1,
},
commentCreator: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: [true, "comment must belong to a user."],
},
postCommentedOn: {
type: mongoose.Schema.ObjectId,
ref: "Post",
required: [true, "a comment must belong to a post"],
}, } )

//data type for post is

const postSchema = new mongoose.Schema(
{
postContent: {
type: String,
required: [true, "Post Content cannot be empty"],
},
postTitle: {
type: String,
required: [true, "Post Title cannot be empty"],
},
vote: {
type: Number,
default: 1,
},
createdAt: {
type: Date,
default: Date.now(),
},
postCreator: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: [true, "a post must belong to a user."],
},
image: {
type: String,
},
},)

我需要通过userId过滤帖子列表和评论列表。我传递userId参数作为postCreator和commentCreator。我做错了什么?

let filter = {};
if (req.params.postId || req.params.userId)
filter = {
postCommentedOn: req.params.postId,
postCreator: req.params.userId,
commentCreator: req.params.userId,
};

从数据类型,我可以看到postannottedon, postCreator, commentCreator类型为ObjectID。参数以字符串格式接收。所以你需要将它们转换为ObjectId,以便在过滤器中使用。

下面的代码应该会有帮助。

const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;
filter = {
postCommentedOn: ObjectId(req.params.postId),
postCreator: ObjectId(req.params.userId),
commentCreator: ObjectId(req.params.userId),
}

我刚刚向OpenAI JavaScript Codex询问了您的问题。它返回了一个结果,我不知道它是否真的有效。但我想看看这是否真的有效。

/* I need to filter a list of posts and a list comments by userId. Am passing the userId params as postCreator and commentCreator */
var posts = [
{
id: 1,
title: 'Post 1',
body: 'Post 1 body',
userId: 1
},
{
id: 2,
title: 'Post 2',
body: 'Post 2 body',
userId: 2
},
{
id: 3,
title: 'Post 3',
body: 'Post 3 body',
userId: 1
}
];
var comments = [
{
id: 1,
body: 'Comment 1',
userId: 1
},
{
id: 2,
body: 'Comment 2',
userId: 2
},
{
id: 3,
body: 'Comment 3',
userId: 1
}
];
var postCreator = 1;
var commentCreator = 1;
var filteredPosts = posts.filter(function(post) {
return post.userId === postCreator;
});
var filteredComments = comments.filter(function(comment) {
return comment.userId === commentCreator;
});
console.log(filteredPosts);
console.log(filteredComments);

如果这不起作用,请原谅我。如果有的话告诉我。谢谢。

相关内容

  • 没有找到相关文章

最新更新