我有一个用户架构,包含书籍,并且我想获取一个用户的书籍清单
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不是用户的功能。
答案 0 :(得分:1)
用户是一个对象,您想在其中映射books数组。
const books = user.books.map(book => book.title)
也可以将find
更改为findById
,因为您只需要1条记录。
如有疑问,请在其中放入console.log,以查看该值是否符合您的期望。
答案 1 :(得分:0)
User.find({id:req.params.user_id}, (err, user) => {
var books = user.map((item) => {return item.title;});
});
尝试上面的一个