【问题标题】:How to get sub document only in mongoose?如何仅在猫鼬中获取子文档?
【发布时间】:2017-11-24 13:11:58
【问题描述】:

我正在尝试从具有以下架构的数组中仅提取子文档:

const UserSchema = Schema({
name: {
    type: String
},library:[{
    story:{type: Schema.Types.ObjectId,ref: 'Story'}
}],
});

我尝试使用:

module.exports.getUserStories = function(userId, callback){
    User.findOne({_id: userId },callback)
    .select('library.story')
};

它给出了这个结果:

    {
  "_id": "5949615072e15d2b34fa8f9d",
  "library": [
    {
      "story": "592ae46cf2a0ba2b208cb092"
    },
    {
      "story": "592ae608df26d80790092fe9"
    },
    {
      "story": "592ae46cf2a0ba2b208cb092"
    }
  ]
}

但我期望得到的只是这个:

[
  {
    "story": "592ae46cf2a0ba2b208cb092"
  },
  {
    "story": "592ae608df26d80790092fe9"
  },
  {
    "story": "592ae46cf2a0ba2b208cb092"
  }
]

我已经尝试过使用双重选择,例如:

module.exports.getUserStories = function(userId, callback){
    User.findOne({_id: userId },callback)
    .select('library.story')
    .select('story')
};

但是结果是一样的

【问题讨论】:

  • 即使我调用了 .populate() 我仍然在顶部获得库

标签: json node.js mongoose


【解决方案1】:

试试这个:

module.exports.getUserStories = function(userId, callback){
    User.find({_id: userId },{'library.story'}).then(function(user){
        if(user){
            callback(user.library);
        }});
};

文档here

【讨论】:

    【解决方案2】:

    此输出预计将通过“选择”返回,但您只需按照您的需要准备返回的数据,如下所示:

    User.findOne({_id: userId }).select('library').then(function(result){
      if(result){
        //If there is returned item
        var stories = result.library;
        //Continue ...
      }
    
    },function(error){
      //Error handling
    })
    

    【讨论】:

    • 这似乎是正确的,但是当我尝试 console.log() 时,我在 result.library 上没有定义
    • 应该可以,你的代码好像有问题发给我
    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2019-10-06
    • 2021-05-08
    • 1970-01-01
    • 2020-07-25
    相关资源
    最近更新 更多