如何只在猫鼬中获得子文件? [英] How to get sub document only in mongoose?

查看:107
本文介绍了如何只在猫鼬中获得子文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to extract only sub document from an array has the following schema :

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"
    }
  ]
}

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

but what i'm expecting to get is only this :

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

我已经尝试过使用像这样的双重选择:

I already tried to use double selection like :

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

但是给出的结果相同

推荐答案

尝试以下方法:

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

文档此处

这篇关于如何只在猫鼬中获得子文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆