简体   繁体   English

如何从Mongodb到Mongoose的嵌套文档中获取Nodejs中的数组?

[英]How to get an Array in Nodejs from a nested document in Mongodb through Mongoose?

I'm trying to get just the emails in the form of an array, from a mongoose Model object. 我试图从一个mongoose Model对象中获取数组形式的电子邮件。 So I can loop the array in a query and get all the posts from the other users in a time sorted order, I'm new to node JS and Javascript. 所以我可以在查询中循环数组并按时间排序顺序获取其他用户的所有帖子,我是节点JS和Javascript的新手。 Here's the code, and the schema: 这是代码和架构:

This is the schema: 这是架构:

var userSchema = mongoose.Schema({

_id:                {type: String, default: mongoose.Types.ObjectId()},
email:              {type: String},
userProfile:       userProfileSchema
});

var userProfileSchema = mongoose.Schema({

friendNetwork:      [{

"email": String, 
"chatId": String, 
"name": String

}],

posts:              [{
                        "_id" : {type: String, default: mongoose.Types.ObjectId()},
                        "postCreator" : String,
                        "isShared" : {type: String, default: ""},
                        "timestamp": String,
                        "text": String,
                        "images": [String],
                        "videos": [String],
                        "likes": [String],
                        "comments": [{

                            "status": {type: Boolean, default: true},
                            "commentId" : {type: String, default: mongoose.Types.ObjectId()},
                            "commentCreator": String,
                            "comment": String,
                            "timestamp": String,

                        }],
                        "shares": [String],
                        "isDelete" : {Boolean, default: false},
                        "isOnlyMe": {Boolean, default: false}

                    }],

isDelete:           {type: Boolean, default: false}
});

I tried the map function but, I get the error "TypeError: Cannot read property 'map' of null". 我尝试了map函数但是,我收到错误“TypeError:无法读取属性'map'的null”。

This is the code: 这是代码:

app.get('/newsfeed/getfeed', (req, res, err) => {

try
{
    // active user email in query
    userModel.findOne({email: req.query.email}, (user) => { 

    // array to get email of all active user's friends
    let userEmails = user.map(user => user.userProfile.friendNetwork.email);       

    //traverse through all friends and get their respective posts shared with friends
    userModel.find({email : { $in: userEmails }}, (err,users) => {

            users.userProfile.posts.find({ isOnlyMe: false }, (posts) => {
                // Mongo Atlas already ordered by timestamp, no need to add further sorting
                res.send(posts);
            });
        });                    
    });  
}
catch 
{
    console.log(err);
    logger(err, "Getting newsfeed of main page failed.");
}  

}); });

The first parameter provided in a callback is typically an error value. 回调中提供的第一个参数通常是错误值。 You should change the line of code to: 您应该将代码行更改为:

userModel.findOne({email: req.query.email}, (err, user) => {

You can view the documentation for that function here: https://mongoosejs.com/docs/api.html#model_Model.findOne 您可以在此处查看该功能的文档: https//mongoosejs.com/docs/api.html#model_Model.findOne

Found the solution, apparently I wasn't passing an array to the map function. 找到解决方案,显然我没有将数组传递给map函数。 map function only accepts and works through an array. map函数只接受并通过数组工作。

app.get('/newsfeed/getfeed', (req, res, err) => {

try
{
    // active user email in query
    userModel.findOne({email: req.query.email}, (err,user) => { 

    // array to get email of all active user's friends
    ***let userEmails = user.userProfile.friendNetwork.map((friend) =>{***
        return friend.email;
    });       

    userEmails.push(req.query.email);

    console.log(userEmails);        
    //traverse through all friends and get their respective posts shared with friends
    userModel.find({ email: { $in: userEmails }}, (err,users) => {

            console.log(users);
            users.userProfile.posts.find({ isOnlyMe: false }, (err,posts) => {
                // Mongo Atlas already ordered by timestamp, no need to add further sorting
                res.send(posts);
            });
        });                    
    });  
}
catch 
{
    console.log(err);
    logger(err, "Getting newsfeed of main page failed.");
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 MongoDB 中的数组中获取嵌入文档(使用 Mongoose) - How to get embedded document in an array in MongoDB (with Mongoose) MongoDB和Mongoose:文档参考ID的嵌套数组 - MongoDB and Mongoose: Nested Array of Document Reference IDs 如何在 mongoose 中创建子文档? MongoDB,NodeJS - How to create sub document in mongoose? MongoDB, NodeJS 如何在Mongoose MongoDb NodeJS中的数组中获取集合中的连接对象 - How to get the connected objects within a collection in an array in Mongoose MongoDb NodeJS 尝试在 Nodejs 上使用 mongoose 在 MongoDB 中保存嵌套文档 - Trying to save nested document in MongoDB using mongoose on Nodejs 使用findOne()后如何从mongoose / mongodb文件中获取值 - How to get the value from a mongoose/mongodb document after using findOne() 如何在nodejs中使用mongoose将对象数组和嵌套对象数组插入mongodb - how to insert array of objects and array of nested objects into mongodb using mongoose in nodejs 如何通过猫鼬使用mongoose从mongoDB获取字段的值 - How to get the value of a field from mongoDB using mongoose through javascript 如何填充嵌套在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 中的对象数组中的文档? - How to populate document nested in array of objects in Mongoose? 如何更新数组中的嵌套 object (Mongoose/MongoDB) - How to update nested object in array (Mongoose/MongoDB)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM