Mongoose - update after filling (Cast Exception)

I cannot update my mongoose scheme due to CastERror, which makes sense, but I do not know how to solve it.

Trip Scheme:

var TripSchema = new Schema({
    name: String,
    _users: [{type: Schema.Types.ObjectId, ref: 'User'}]
});

Custom Scheme:

var UserSchema = new Schema({
    name: String,
    email: String,
});

on my html page I spend a trip with the ability to add new users to this trip, I retrieve the data by calling the findById method in the diagram:

exports.readById = function (request, result) {
    Trip.findById(request.params.tripId).populate('_users').exec(function (error, trip) {
        if (error) {
            console.log('error getting trips');
        } else {
            console.log('found single trip: ' + trip);
            result.json(trip);
        }
    })
};

it works. In my ui, I can add new users to the trip, here is the code:

var user = new UserService();
user.email = $scope.newMail;
user.$save(function(response){   
    trip._users.push(user._id);
    trip.$update(function (response) {
        console.log('OK - user ' + user.email + ' was linked to trip ' + trip.name);

        // call for the updated document in database
        this.readOne();
    })
};

The problem is that when I update my scheme, existing users on the trip fill up, which means they are stored as objects, not the id on the trip, the new user is stored as ObjectId on the trip. How can I make sure that populated users return to the ObjectId before updating? otherwise, the update will fail using CastError.

see here for error

+4
2

, , , , , . , , :

. trip._users.push(user._id); . , , , .

-, - push(user._id), : push(user). , _users , .

, . , $update, trip._users ObjectIds. , "un-populate" _users:

user_ids = []
for (var i in trip._users){
    /* it might be a good idea to do more validation here if you like, to make
     * sure you don't have any naked userIds in this array already, as you would
     */in your original code.
    user_ids.push(trip._users[i]._id);
}
trip._users = user_ids;
trip.$update(....

, , , , ? , , , , ObjectId, .

+2

, , ObjectId. NodeJS, async.js. :

let converter = function(array, callback) {
  let idArray;
  async.each(array, function(item, itemCallback) {
    idArray.push(item._id);
    itemCallback();
  }, function(err) {
    callback(idArray);
  })
};

, , .

0

All Articles