Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using MeanJS and have run into a snag. I'd like to use the $update function of the $resource service in Angular that MeanJS provides, if possible. Here's a very simplified version of what I'm trying to do:

Mongoose schema:

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

var Lotion = new Schema({
  name: String;
});
var BasketSchema = new Schema({
  lotions: [{
    type: Schema.ObjectId,
    ref: 'Lotion'
  }]
});

Angular: Note that I already retrieved the Lotion object and the Basket object upon page load and am now simply trying to add the Lotion object to the lotions array of basket.

$scope.putTheLotionInTheBasket = function(lotion, basket){
  basket.lotions.push(lotion);
  basket.$update(function(data){
                //success
            },
            //failure
            function(error){
                $scope.error = error.data.message;
            }
  )
}

As you can see, this won't work. It returns a 400 with Cast to ObjectId failed for value "[object Object]" at path "agencies", name:CastError,…}

Is there a simple but right way to do this? Do I have to create a new REST endpoint and $resource function and pass the lotion ID to do a lookup on the server, even though I already have both objects on the client side?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

I'm embarrassed at the simplicity of the solution, but here it is. Since Mongoose will internally cast a valid hex object ID string to a Mongoose.Schema.ObjectId, I can simply replace

basket.lotions.push(lotion);

with

basket.lotions.push(lotion._id);

and MEANJS and Mongoose do the rest of the heavy lifting for me. Simple... and only took me a few days to figure it out :/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.