gpt4 book ai didi

javascript - 使用 mongoose 返回特定用户的所有评论,而无需其他文档字段

转载 作者:行者123 更新时间:2023-11-28 02:37:26 25 4
gpt4 key购买 nike

var mongoose = require('mongoose');

// defines the database schema for this object
var schema = mongoose.Schema({
projectName : String,
authorName : String

comment : [{
id : String,
authorName : String,
authorEmailAddress : { type : String, index : true }
}]
});

})

// Sets the schema for model
var ProjectModel = mongoose.model('Project', schema);

// Create a project
exports.create = function (projectJSON) {

var project = new ProjectModel({

projectName : projectJSON.projectName ,
authorName : projectJSON.authorName,

comment : [{
id : projectJSON.comments.id,
authorName : projectJSON.comments.authorName,
authorEmailAddress : projectJSON.authorEmailAddress
});

project.save(function(err) {
if (err) {
console.log(err);
}
else{
console.log("success");
}
});


}

问:我想检索特定用户在所有项目中发表的所有评论(没有其他文档字段)

我的尝试:

// assuming email address is unique per user, as user can always change displayName for instance

exports.allCommentsByUser = function(userEmail, callback){
ProjectModel.find(
{"comments.authorEmailAddress" : userEmail},
{ "projectName" : 1, "comments.authorEmailAddress" : 1 },
callback);
};

最佳答案

您可以对此类查询使用 2.2 聚合框架:

ProjectModel.aggregate([
{
// Only include the projectName and comments fields.
$project: { 'projectName': true, 'comments': true, '_id': false }
}, {
// Get all project docs that contain comments by this user
$match: { 'comments.authorEmailAddress': userEmail }
}, {
// Duplicate the project docs, one per comment.
$unwind: '$comments'
}, {
// Filter that result to just the comments by this user
$match: { 'comments.authorEmailAddress': userEmail }
}], callback
);

关于javascript - 使用 mongoose 返回特定用户的所有评论,而无需其他文档字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13273619/

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