0

i have an array inside my NetworkSchema which i am trying to update with another entry using findOneandupdate in mongoose

My model:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var NetworkSchema = new Schema({

UserID: {
    type: String,
    default: '',
    trim: true
},
NetworkList: [{
    Fid: {

        type: Schema.ObjectId,
        ref: 'User'
    }
}]});

Html:

<div ng-controller="AuthenticationController" style="margin-top: 50px">

<div ng-controller="NetworksController">
    <ul>

        <li ng-repeat="Network in Networkfriends">

            {{Network.firstName}}
            <button type="submit" class = "btn btn-default" data-ng-click="update(Network._id)">Add as a Friend</button>
        </li>
    </ul>
    <button type="submit" ng-click="showlist()">show</button>
</div>
</div>

Network Controller:

$scope.update = function(FriendID)
    {
        var UserID = this.authentication.user._id;
        console.log('User ID :' +UserID);
        var NetworkList = [{

            Fid: this.FriendID
        }];

        $http.post('/networks/update',{UserID: UserID, FriendID: FriendID}, $scope.credentials).success(function(response){
            console.log(JSON.stringify(response));

        });
}

Network.Server.Controller:

var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    Network = mongoose.model('Network'),
    _ = require('lodash');
    util = require('util');

exports.update = function(req, res) {

var query={'UserID':req.body.UserID};


var NetworkList = [{Fid: req.body.FriendID}];
var update = {'NetworkList' :NetworkList};


Network.findOneAndUpdate(query,update,function(err){
    if (err) {
        return err;
    } else {
        NetworkList.push(req.body.FriendID);

    }
});
};

i want to add the objectID of user from usersList which i am getting from NetworkFriends in my HTML page as you can see above, whenever i click Add as a Friend button and what i am getting is a new entry in my database with ObjectID of NetworkFriend and i want comma separated objectID's of more than one NetworkFriend through Add as a Friend button

Here is the entry in My Database:

{
"NetworkList" : [ 
    {
        "Fid" : ObjectId("5486fab40bc27314276be8cf"),
        "_id" : ObjectId("548d6ed5d6994cac219f536f")
    }
],
"UserID" : "547eaaab6c39471c3f5aebb6",
"__v" : 0,
"_id" : ObjectId("548adbc8b7eac44013bf188d")

}

My aim is:

 {
"NetworkList" : [ 
    {
        "Fid" : ObjectId("5486fab40bc27314276be8cf"),"(objectID of another friend with comma separated like this"),
        "_id" : ObjectId("548d6ed5d6994cac219f536f")
    }
],
"UserID" : "547eaaab6c39471c3f5aebb6",
"__v" : 0,
"_id" : ObjectId("548adbc8b7eac44013bf188d")

}

1 Answer 1

1

What you're aiming for isn't a valid structure. What you likely want instead is a schema where NetworkList directly contains an array of ObjectIds of the user's friends:

var NetworkSchema = new Schema({
    UserID: {
        type: String,
        default: '',
        trim: true
    },
    NetworkList: [{
        type: Schema.ObjectId,
        ref: 'User'
    }]
});

Your docs would then look like:

{
    "_id" : ObjectId("548adbc8b7eac44013bf188d"),
    "NetworkList" : [ 
        ObjectId("5486fab40bc27314276be8cf") 
    ],
    "UserID" : "547eaaab6c39471c3f5aebb6",
    "__v" : 0
}

Then you can add a new friend to NetworkList using the $push operator like this:

exports.update = function(req, res) {
    var query={'UserID': req.body.UserID};
    var update = {$push: {'NetworkList': req.body.FriendID}};

    Network.findOneAndUpdate(query, update, function(err, doc){ ... });
};
Sign up to request clarification or add additional context in comments.

4 Comments

A big Thanks for answer. But when i am trying your solution, ObjectID of user is going to server controller but not saving in my database, this is my findOneandUpdate Network.findOneAndUpdate(query,update,function(err){ if (err) { return err; } else{ console.log('hahahahaha'); } }); can you tell me where i am going wrong?
Instead of return err;, call console.log(err); so you can see any errors.
it worked by using find and update separately, can you explain me how to use post save middleware in mongoose as i am trying to switch UserID and FriendID after save. i was trying to use NetworkSchema.post('save',function(){ NetworkSchema.find({'to': this.FriendID},function(err){ if(err){ return err; } }); NetworkSchema.update({'from': this.UserID},function(err){ if(err){ return err; } }); console.log('post save working'); }); It is now working for now can you suggest me where i am wrong
Glad you got it working. It would be best to post the question about middleware as a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.