简体   繁体   中英

Mongoose: How to create a document and simultaneously push a sub array into it

I am trying to seed a mongo database with users and the users friends.

Users is it's own Model (with a ref to the Friends model).

I have two arrays of data to use to seed the database. The friends array contains sub arrays. Each subarray –in order– contains the friends for the respective user array. ie friends[0] are the friends for user[0].

The goal is to create the user, then search to determine if the users friends document exist all-ready. If they don't, create the friend document, and push them to that user.

The code creates the users, but only creates the friends from the friends[0]. It seems to do with async, but have not idea where to go next.

   function doSomething(){
        var i = 0;
        userArray.forEach(function(user){
            User.create(user, function(err, createdUser){
                if(err){
                    console.log(err);
                }
                console.log(createdUser.name + ' created!');
                var incrementer = 0;
                for(let friend of friends[i]){
                    Friend.find({name: friend.name}, function(foundFriend){
                        if(foundFriend == undefined){
                            Friend.create(friend, function(err, createdFriend){
                                createdUser.friends.push(createdFriend);
                                createdUser.save;
                                console.log(createdFriend.name + ' added to' + createdUser.name + ' friends!');
                                incrementer++;
                                if(incrementer === friends[i].length){
                                        i++; 
                                    }                                        
                            });
                        }
                    });
                }
            });
        });
    }

    //Output I would expect (assuming no documents exist)

    //John Smith created!
    //Sally added to John Smith friends
    //Mike added to John Smith friends

    //Mary Doe created!
    //Bob added to Mary Doe friends!
    //Gary added to Mary Doe friends!

    //Instead I am getting (assuming no matching documents exist)

    //John Smith created!
    //Mary Doe created!


    //Sally added to John Smith friends!
    //Sally added to Mary Doe friends!
    //Mike added to Mary Doe friends!
    //Sally added to Mary Doe friends!

This last part of output is random and changes with each run.

I would split your loop into two separate tasks. PS Consider to save not user.friends but user.friendsIDs (its more common)

 var users = [ {name: 'user 1'}, {name: 'user 2'} ]; var friends = [ [{name: 'Alex'}, {name: 'John'}], [{name: 'Alex'}, {name: 'Max'}] ]; // save all friends first var flattenFriends = [].concat.apply([], friends); var names = []; var filteredFriends = flattenFriends.filter(function(friend, i) { if(names.indexOf(friend.name) > -1) return false; names.push(friend.name); return true; }); filteredFriends.forEach(function(friend) { Friend.find({name: friend.name}, function(found) { if(!found) { var newFriend = new Friend(friend); newFriend.save(); } }); }); // save all users (with friends) users.forEach(function(user, i) { var user = user; user.friends = []; friends[i].forEach(function(friend, j) { Friend.find({name: friend.name}, function(found) { user.friends.push(found) }) }); var newUser = new User(user); newUser.save(); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM