David
David

Reputation: 61

MeanJS: setting Mongoose object reference in array in Angular

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?

Upvotes: 0

Views: 1519

Answers (1)

David
David

Reputation: 61

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

Upvotes: 6

Related Questions