【问题标题】:getting back array of object data in a specific format from a mongoose query从猫鼬查询中获取特定格式的对象数据数组
【发布时间】:2017-10-09 00:48:09
【问题描述】:

使用 Mongoose 和 express,在检索朋友列表时,

我正在以我需要简化的格式取回我不需要的数据

  1. 如何在好友子文档中隐藏_id和状态?

  2. 我想要一个对象数组来填充每个对象的 id 字段,而不是其他所有内容,包括架构中的 _id 和状态。

例如。

var friends = [{firstName: "User 1", lastName: "User 1", username: "user1"}, {firstName: "User 2", lastName: "User 2", username: "user2"}]

目前看起来是这样的

var UserSchema = new Schema({
  friends: [
    { 
      id: 
        { 
          type: Schema.Types.ObjectId, ref: 'User'}, 
          status: Number 
        }
    }
  ]
});

app.get('/getFriends', requireLogin, function(req, res) {
  User.findOne({ _id: req.user.id }, 'friends')
	.populate({
	  path: 'friends.id',
		model: 'User',
		select: 'username firstName lastName -_id'
	})
	.exec(function(err, friends) {
	  res.json(friends);
	}) 
})

friends: [ 
  { 
    id: [Object], 
    status: 2, 
    _id: 590bbb88858367c9bb07776e 
  },
  { 
    id: [Object], 
    status: 2, 
    _id: 590bbb95858367c9bb07776f 
   }
]

id Object
firstName: "User 1", lastName: "User 1", username: "user1"

【问题讨论】:

    标签: javascript json mongodb express mongoose


    【解决方案1】:

    使用选择功能只选择你想要的属性

    .select('firstName lastName username').exec(function(err, friends) {
          res.json(friends);
    }) 
    

    或使用mapdelete 的组合来删除键/值对

    var friends = [{
        id: 1,
        status: 2,
        _id: 590 
      },
      {
        id: 2,
        status: 2,
        _id: 590 
      }
    ];
    
    friends = friends.map(function(v) {
     delete(v._id);
     return v;
    });
    
    console.log(friends);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 2021-12-18
      • 1970-01-01
      • 2014-09-10
      • 2021-08-23
      • 2018-01-26
      • 2017-03-28
      • 2014-04-21
      相关资源
      最近更新 更多