0

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?

1 Answer 1

6

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 :/

Sign up to request clarification or add additional context in comments.

Comments

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.