Wednesday, 5 April 2017

Node.js Mongoose how to save new document and add new value to array field

I have a User model and each user document has name field which is String and friends field which is an array of integers which holds id's of other users who this user is friends with.

Whenever I want to create a new user document with one id already in friends array, I have to three steps: 1. create new user with specific name; 2. save this user; 3. update this user's friends field by adding new friend id to the array.

I was wondering if there is another, more efficient way of achieving the same result. Here is my code so far:

var User = mongoose.model('User',{
    friends:  {
        type: [Number],
        required: false      
    },
    name: String
});

            //cretae new user document
            var user = new User ({
                name: name
            });

            user.save(function(err){
                if(err){
                    console.log("something went wrog, read below");
                    console.log(err);
                }else{
                    User.update({'name': name}, {
                        $addToSet: { 'friends': newFriendId}
                    },function(err, count) {
                        if(err){
                            console.log(err);
                        }else{
                            console.log(count);
                        } 
                    }); 
                }
            });



via Nikolaj

No comments:

Post a Comment