最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

猫鼬:从模型中的对象数组中,将属性的值提取为数组

运维笔记admin7浏览0评论

猫鼬:从模型中的对象数组中,将属性的值提取为数组

猫鼬:从模型中的对象数组中,将属性的值提取为数组

我有一个用户架构,包含书籍,并且我想要获取一个用户的书籍清单

var userSchema = new Schema({
    id: {
        type: String,
        unique: true,
        required: true
    },
    gender: String,
    firstName: String,
    lastName: String,
    books: [{
        id: String
        title: String
        author: String
    }]

});

例如,

[{id: "1",
  gender: "Male",
  firstName: "Alan",
  lastName: "Brown",
  books: [
    { id: "ISN001",
      title: "Programming From Beginer to Give Up",
      author: "Someone"
    },
    { id: "ISN002",
      title: "Introduction to Databases",
      author: "BetaCat"
    }
  ]
},
{ id: "2",
  gender: "Female",
  firstName: "Cynthia",
  lastName: "Durand",
  books: [
    { id: "ISN003",
      title: "How to Play with Your Cat",
      author: "UrCat"
    },
    { id: "ISN004",
      title: "Greek Mythology",
      author: "Heracles"
    }
  ]
}]

我可以通过req.params.user_id获取用户ID,并返回该用户的书单数组。例如,如果我获得user_id 1,我想要["Programming From Beginer to Give Up","Introduction to Databases"]。我尝试通过

做到这一点
var getBookList = (req, res) => {
    User.find(req.params.user_id, (err, user) => {
        var books = user.map((item) => {return item.title;});
    });
}

但是不起作用,因为map不是用户的功能。

回答如下:
User.find({id:req.params.user_id}, (err, user) => {
    var books = user.map((item) => {return item.title;});
});
发布评论

评论列表(0)

  1. 暂无评论