0

I am using Mongodb. When I want to update fields I am getting the following error Cast to ObjectId failed for the value:

[object Object],[object Object],[object Object].

When post is empty let me to update all the properties while somebody post somethings then I am not able to update provider properties and I am getting following error:

View which have used modal from ui bootstapt.

<label class="col-lg-2 control-label">Company Name</label>
        <div class="col-lg-10">
          <input name="name" type="text" ng-model="provider.name" minlength="4" class="form-control" placeholder="Amazon Web Services" required>
          <span class="help-block" ng-show="cspRegister.name.$dirty &&  cspRegister.name.$invalid"> Not valid name!</span>
        </div>
      </div>
      <div class="form-group">
        <label class="col-lg-2 control-label">Abbreviated company name</label>
        <div class="col-lg-10">
          <input name="abbreviated" type="text" ng-model="provider.abbreviated" class="form-control" placeholder="AWS" >
        </div>
      </div>
      <div class="form-group">
        <label class="col-lg-2 control-label">Home page</label>
        <div class="col-lg-10">
          <input name="url" type="url"  ng-model="provider.url" class="form-control" placeholder="http://aws.amazon.com/" required>
          <span class="help-block" ng-show="cspRegister.url.$error.url"> Not valid url!</span>
        </div>
      </div>
      <!--start point of muli select-->
      <div class="form-group">
        <label class="col-lg-2 control-label">Product name</label>
        <div class="col-lg-10">
          <select name="services"  multiple ng-model="provider.services" class="form-control" required >
            <option value="paas">Paas</option>
            <option value="saas">Saas</option>
            <option value="dbaas">Dbaas</option>
          </select>
        </div>
      </div>
      <div class="form-group">
        <label  class="col-lg-2 control-label">Location</label>
        <div class="col-lg-10">
          <select multiple  ng-model="provider.locations" class="form-control" class="form-control" required>
            <option ng-repeat="item in locations" value="{{item.name}}">{{item.name}}</option>
          </select>
          <span class="help-block">A longer block of help text that breaks onto a new line and may extend beyond one line.</span>
        </div>
      </div>
      <!--end of multi selector-->
      <div class="form-group">
        <label class="col-lg-2 control-label">Description</label>
        <div class="col-lg-10">
          <textarea name="description" ng-model="provider.description" class="form-control" rows="3" required></textarea>
        </div>
      </div>
    </form>
</div>
<div class="modal-footer">
    <button ng-click="updateProvider(provider);ok()" class="btn btn-success"><i class="icon-white icon-plus"></i> Update & Close</button>
    <button ng-click="cancel()" class="btn btn-warning">Cancel</button>
</div>

Provider Schema

var ProviderSchema = new Schema({
  name: String,
  abbreviated: String,
 // company:String,
  services: {type : Array, default:[]},
  locations: {type : Array, default:[]},
  description: String,
  url: String,
  author: String,
  upvotes: { type:Number, default:0 },
  upvoteUser:{type : Array, default:[]},
  createdOn: { type: Date, default: Date.now },
  certificates:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Certificates' }],
  posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
});

ProviderSchema.methods.findByName = function (cb) {
  return this.model('Provider').find({ name: this.name }, cb);
}
ProviderSchema.methods.upvote = function(cb) {
  this.upvotes += 1;
  this.save(cb, function(error) {
    if(error){
      console.error("Error saving object: ", error)
    }
  });
};

This is update in factory

ob.updateProvider = function (provider) {
       return $http.put('/api/providers/' + provider._id , provider, {
            headers: {Authorization: 'Bearer '+Auth.getToken()}
            }).success(function(provider){
       })
    };

and this is update function in my api

exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Provider.findById(req.params.id, function (err, provider) {
    if (err) { return handleError(res, err); }
    if(!provider) { return res.send(404); }

    var updated = _.merge(provider, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, provider);
    });
  });
};

This is what I have in my controller.

$scope.updateProvider = function (updatedProvider) {
                var provider = updatedProvider;
                providers.updateProvider(provider)
                  .success(function () {
                    providers.getAll();
                    $scope.status = 'Updated provider! Refreshing provider list.';
                  })
                  .error(function(err, status) {
                    console.log(err);
                    console.log(status);
                  });
              };

This is what is result for updated:

 abbreviated: 'aws',
  _id: 55663fc20e9009c82dccba94,
  company: 'http://dbpedia.org/resource/SnapLogic',
  name: 'SnapLogic',
  description: 'SnapLogic is a commercial software company that provides data an
 2006. SnapLogic is headed by Ex-CEO and Co-Founder of Informatica, Gaurav Dhill
  __v: 25,
  posts:
   [ { upvotes: 4,
       upvoteUser: [Object],
       comments: [Object],
       __v: 16,
       author: 'Juan y Maryam',
       body: 'cc',
       title: 'cczzs',
       _id: '5569f716a4c7bbd4219a3303' },
     { upvotes: 4,
       upvoteUser: [Object],
       comments: [],
       __v: 4,
       author: 'Juan y Maryam',
       body: 'zzaaa',
       title: 'juan',
       _id: '5569fb10c61b1af02fa1cc39' },
     { upvotes: 4,
       upvoteUser: [Object],
       comments: [],
       __v: 4,
       author: 'Juan y Maryam',
       body: 'xxxxx',
       title: 'xxxxxxxxxx',
       _id: '5569fb15c61b1af02fa1cc3a' },
     { upvotes: 2,
       upvoteUser: [Object],
       comments: [],
       __v: 2,
       author: 'Test User',
       body: 'nnnnnnnnnnnnnnnn',
       title: 'ooooooooooooo',
       _id: '5569fcd3335d49d82ccef9cd' },
     { upvotes: 1,
       upvoteUser: [Object],
       comments: [],
       __v: 1,
       author: 'Editor',
       body: 'ss',
       title: 'sssssss',
       _id: '556a07892d62dadc182fcc1f' },
     { upvotes: 1,
       upvoteUser: [Object],
       comments: [],
       __v: 1,
       author: 'maya beaty',
       body: 'ssssssss',
       title: 'ssssssss',
       _id: '556a07f92d62dadc182fcc23' },
     { upvotes: 1,
       upvoteUser: [Object],
       comments: [],
       __v: 1,
       author: 'Maryam Pashmi',
       body: 'z',
       title: 'z',
       _id: '556a13e62848566023f03e6d' },
     556a07f92d62dadc182fcc23,
     556a13e62848566023f03e6d ],
  certificates: [],
  createdOn: Thu May 28 2015 00:05:54 GMT+0200 (Romance Daylight Time),
  upvoteUser: [ 'maya beaty', 'Maryam Pashmi', 'Juan y Maryam' ],
  upvotes: 3,
  locations: [ 'Åland Islands', 'Albania' ],
  services: [ 'saas' ] }
PUT /api/providers/55663fc20e9009c82dccba94 500 10ms

Is there any one who know why I am getting this error and what issue I have to change in my schema?

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
pm1359
  • 622
  • 1
  • 10
  • 31
  • Need to see your schema definition, and your view code where you're generating the new content (fields/value) for `provider` to be updated to. Generally the error means somwehere where an objectID(5562ff…) was supposed to go, it's passing a string "[object Object],.." which itself seems like an object got converted into string. My guess is you meant to use that object but instead used its parent object – laggingreflex Jun 01 '15 at 13:10
  • @laggingreflex appreciated for your answer. I updated my question. – pm1359 Jun 01 '15 at 14:34
  • Could you put a `console.log(updated)` and show its output? right after `var updated = _.merge(provider, req.body)` in your update function in your api – laggingreflex Jun 01 '15 at 15:12
  • @laggingreflex i updated question with value of update. – pm1359 Jun 01 '15 at 15:39

1 Answers1

2

I don't have a solution but I can try to explain what the problem is, or at least why it isn't working in your case. Although there's couple of solutions at the end that may or may not work..

Your provider.posts is an array of another set of documents referenced by "Posts", as defined in your Provider schema.

posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }]
posts: [
  {upvotes: 4, ... title: 'cczzs', _id: '5569f716a4c7bbd4219a3303' }, 
  {upvotes: 4, ... title: 'juan', _id: '5569fb10c61b1af02fa1cc39' }, 
  {upvotes: 4, ... _id: '5569fb15c61b1af02fa1cc3a' }, 
  ...
  {upvotes: 1, _id: '556a13e62848566023f03e6d' }, 
  556a07f92d62dadc182fcc23, 
  556a13e62848566023f03e6d
],

These are actually supposed to be saved as just IDs (556a07…), because that's how they're defined in your Schema

Actually if you look towards the end there are some elements which are actually just IDs (556a07f92d62da…), those are probably the ones fetched from the database, and the others are _.merged from req.body

The problem is that when saving, these objects are being converted to string "[Object object]" for some reason. This isn't supposed to happen or at least doesn't happen with me. I have mongoose@3.8 installed, so check if maybe you're on an older version.

Just to make sure this is exactly the root cause of the problem, you should

delete req.body.posts;
var updated = _.merge(provider, req.body);
// now updates.posts should only have 2 IDs mentioned above
updated.save(...

and see if it gets saved.

Anyways going through older questions you'll find some have had luck with deleting and re-creating the entire collection. Some advise that it's bad idea to store them as objects in the first place, in which case you can actually .map these objects and convert them to their native string ID or ObjectID before saving.

updated.posts = updated.posts.map(function(post){return post._id});
updated.save(...

Hope that helps out in some way even if it doesn't solve it.

Community
  • 1
  • 1
laggingreflex
  • 32,948
  • 35
  • 141
  • 196