我试图从数组中仅提取子文档具有以下模式:
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')
};
但是给出了相同的结果
答案 0 :(得分:2)
此输出预计将通过" select"但只是您可以根据需要准备返回的数据,如下所示:
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
})
答案 1 :(得分:2)
试试这个:
module.exports.getUserStories = function(userId, callback){
User.find({_id: userId },{'library.story'}).then(function(user){
if(user){
callback(user.library);
}});
};
文档here