json - 在nodejs中制作json时想要在mongoose记录中添加额外的键

标签 json node.js mongodb mongoose

var commentSchema = new Schema({
    text: String,
    actions:[{actionid:String, actiondata:String}],
    author: String  
})

在获取记录时,我需要计数 action = 1。我想在每个评论中添加计数作为额外的键,如下所示:

{
"comments":[
          {"commentData":{
              "text":"temp1",
              "author":"tempauthor1",
              "actioncount":"2"
           }},
          {"commentData":{
              "text":"temp1",
              "author":"tempauthor2",
              "actioncount":"3"
           }}
]}

我需要这样的 json 响应。请帮忙。

最佳答案

仅过滤 actionid = 1actionid=1 的计数。请尝试通过aggregation进行操作

Comment.aggregate([{$unwind: '$actions'},
                   // filter the actionid is 1
                   {$match: {'actions.actionid': '1'}},
                   // 
                   {$group: {_id: 'actions.actionid',
                             actioncount: {$sum: 1}
                             }}
   ])

关于json - 在nodejs中制作json时想要在mongoose记录中添加额外的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986674/

相关文章:

javascript - 部分未渲染 Express-handlebars Node

node.js - 修复 Ubuntu 上的 npm 全局安装

node.js - MongoDB 创建文档并成功创建另一个文档

c++ - Mongodb Cxx Driver Test 在 Release Build 中崩溃 [在 Debug 中工作正常]

java - 使用 Jackson ObjectMapper 将 Json 的一部分转换为 HashMap

javascript - 无法将数组从 jQuery 发送到 MVC 4 Controller

php - 更好的想法如何从数据库中获取大量 MySql 数据

Java - 如何迭代 json 对象键和值对?

node.js - 找不到模块 'engine.io'

java - 从辅助 mongodb 数据库读取数据