猫鼬节点从文档返回多个引用对象的数组

时间:2019-03-05 23:07:23

标签: javascript node.js mongodb mongoose mongoose-schema

我正在使用Mongoose开发节点后端API。我有2个架构,一个是User架构,另一个是Follow架构(另存为用户,在mongo中也遵循)。 follow模式字段followers和follower包含引用用户对象的ObjectId数组。我试图返回数组中的“引用”对象,以便可以用一个对象向包含一个包含userFollowing和userFollowers数组的客户端的对象进行响应,但是我无法填充输出。

我还需要能够过滤返回的对象以仅返回'username bio image email first_name surname join_date'

我当前的错误输出如下。我不确定查询是否出错或使用的是正确方法。

  

[{_id:5c7dc1b92f3f1dd8ad9df993,       用户:5c7d93b57a29ce05a096c492,       用户关注:[],       userFollowers:[]}]

var mongoose = require('mongoose');

let Schema = mongoose.Schema;

var FollowSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  followers: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }],
  following: [{
    type: Schema.Types.ObjectId,
    ref: 'User'
  }]
}, { toJSON: { virtuals: true } }
);
 
module.exports = mongoose.model('Follow', FollowSchema);

// username must be unique and is required
var UserSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    required: true
  },
  email: {
    type: String,
    unique: true,
  },
  first_name: {
    type: String,
    required: true
  },
  surname: {
    type: String,
    required: true
  },
  join_date: {
    type: Date,
    default: Date.now
  },
  bio: {
    type: String,
    default: 'Tell me about yourself'
  },
  image:{
    type: String,
    default: 'profile.jpg'
  },
  password: {
    type: String,
    required: true
  }

});

User.findOne({
    'username': username
  }, function (err, user) {
    if (!user) {
      return res.json({
        'state': false,
        'msg': `No user found with username ${username}`
      })
    } else {
      const user_id = user._id;
      Follow.aggregate([{
          $match: {
            "user": mongoose.Types.ObjectId(user_id)
          }
        },
        {
          $lookup: {
            "from": "follows",
            "localField": "following",
            "foreignField": "_id",
            "as": "userFollowing"
          }
        },
        {
          $lookup: {
            "from": "follows",
            "localField": "followers",
            "foreignField": "_id",

            "as": "userFollowers"
          }
        }, {
          $project: {
            "user": 1,
            "userFollowers": 1,
            "userFollowing": 1
          }
        }
      ]).exec(function (err, doc) {
        console.log(doc);
        res.json({
          'state': true,
          'msg': 'Follow list',
          'doc': doc
        })
      })
    }
  })

0 个答案:

没有答案