native update in Sails with Mongo does not work with ObjectId

前端 未结 3 775
心在旅途
心在旅途 2020-12-21 05:44

I wonder what I am doing wrong.

I use Sailsv0.10 and mongo2.6.0 and want to update an array field (using $push) in a collection via native.

My model:

3条回答
  •  不思量自难忘°
    2020-12-21 06:23

    The problem is because, in mongo relation field, data stores as string - but should be as ObjectID, e.g. ObjectID("56309f327dc5a4133c54bd5e"). I've tried to generate ObjectID in beforeCreate() function

    beforeCreate: function(values, cb) {
        var ObjectID = require('mongodb').ObjectID;
        values.owner = ObjectID(values.owner);
        cb();
    }
    

    But it throw an error "Argument passed in must be a single String of 12 bytes or a string of 24 hex characters new ObjectId". I had sails-mongo 0.11.2. Then I'v tried to update - and it helped to me. So check your sails-mongo version. Do not forget to remove manual generating ObjectID from beforeCreate() it will deals by itself

    beforeCreate: function(values, cb) {
    
        cb();
    }
    

提交回复
热议问题