sylvain1264
sylvain1264

Reputation: 855

Why PouchDb put(doc) method is editing my parameter?

I have a custom object like this:

function BlobModel(id){
    this._id = id;
    this._rev = null;
    this.filename = '';
    this.index = '';
    this.data = '';
}

If I put it in my pouch database it works fine, but I have a strange issue, if I do this:

var myDoc = new BlobModel('myId');

db.put(myDoc).then(function(){
    console.log(myDoc);
})

console.log result: enter image description here Why I got _rev value and _rev_tree property added to my myDoc parameter, it should be added only in the document inside the db. Why it's not same behavior as a native object ? How to fix it ? The only way I see is to clone my object before putting it, but it's weird on heavy objects.

If I do it with a native object, it won't be modified:

var myDoc = {
    _id: 'myId',
    _rev: null,
    filename: '',
    index: '',
    data: ''
}

db.put(myDoc).then(function(){
    console.log(myDoc);
});

Upvotes: 0

Views: 199

Answers (2)

nlawson
nlawson

Reputation: 11620

PouchDB expects you to insert plain JavaScript objects as your documents. If you try to insert custom classes, then the cloning algorithm will ignore it and you'll start to see strange errors.

My recommendation is to run JSON.parse(JSON.stringify(myDoc)) before you insert it into PouchDB. Either that, or don't use custom classes.

Upvotes: 1

Carlo
Carlo

Reputation: 2112

in JS there is little difference between objects, and PouchDB inserts proprieties to manage the indexing see here.

You could do this..

db.put({ mydoc: myDoc })

but it's really an issue?

Upvotes: 1

Related Questions