如何使用快速js

时间:2018-02-12 18:13:33

标签: node.js mongoose

我试图计算子数组值。所以,我打算在猫鼬中使用聚合函数。当我尝试下面的代码时,我得到了空数组

我想把hitshistory的数量作为命中。它尝试了很多提示,但我无法获得解决方案。

mongodb中的值

> db.posts.find().pretty();
{
    "_id" : ObjectId("5a7b49fddeb8a7175d69bc82"),
    "userId" : "5a68608766f81b133f354b7c",
    "post" : "check 1st",
    "type" : 1,
    "hitsHistory" : [
        {
            "created_at" : ISODate("2018-02-07T18:49:22.404Z"),
            "_id" : ObjectId("5a7b4a32deb8a7175d69bc83"),
            "userId" : "5a68608766f81b133f354b7c"
        },
        {
            "created_at" : ISODate("2018-02-07T18:55:50.112Z"),
            "_id" : ObjectId("5a7b4bb620c4ec1907e55c5e"),
            "userId" : "5a68608766f81b133f354b7c"
        },
        {
            "created_at" : ISODate("2018-02-07T19:01:29.152Z"),
            "_id" : ObjectId("5a7b4d0931e6d11a6408f5c6"),
            "userId" : "5a68608766f81b133f354b7c"
        }
    ],
    "__v" : 0
}

这是我的模特

const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
  userId: {
    type: String
  },
  post: {
    type: String,
    required: true
  },
  type: {
    type: Number,
    required: true,
  },
hitsHistory: [{
    userId: String,
    created_at: {
      type: Date,
      default: Date.now
    },
  }]
});
const Post = module.exports = mongoose.model('Post', PostSchema);

module.exports.getPostByUserid = function(userId, callback){

 Post.aggregate([
    { $match: {
        userId: userId
    }}
    ,
    { $project :{
      userId:1,
      post:1,
      type:1,
      hitsHistory:1,
      hits:{size : "$hitsHistory"}
    }}
    ]).exec(callback);

}

这是我的控制器

exports.ownPost =  (req, res, next) => {
    Post.getPostByUserid(req.user._id,(err, post) => {
      if(err){
        res.json({success:false,posts:post});
      }else{
        res.json({success:true,posts:post});
      }
    });
}

任何人都可以向我展示一些样本,以便将hitshistory的计数作为点击次数

0 个答案:

没有答案