Cyril ALFARO
Cyril ALFARO

Reputation: 1681

Trouble when trying to save an Object on a document with nodejs throught mongoose

I got this schema :

var schema = {
    id                  : { type:Number, unique:true },
    name                : String,
    kind                : String,
    size                : Object,
    skin                : String,
    position            : Object,
    velocity            : Object,
    acceleration        : Object,
    spritesheet         : String,
    animation           : Object,
    animations          : Object,
    currentAnimation    : String,
    visible             : Boolean
};

note : the following this is an instance of a buisness object. this.dao is set like this:

var elementSchema = mongoose.Schema(schema);
this.dao = mongoose.model('Element', elementSchema);

Here you have the way I use to get data :

this.dao.findOne({"id":id},(function(err,result){
    this.data = result;
}).bind(this)) ;

I save like this in my object :

this.data.save((function(err,result,row){
    if(err !== null) throw err;
    if(row === 1) {
        console.log(result);
        this.emit("saved");
    }
}).bind(this)) ;

The problem :

It works very well for a lot of type in schema but I got strange issues with Object type.

When I try to save my data, it works for all but not for Object types. A console.log(this.data.position) shown {x:100,y:200} in console. But if I change data.position like this : data.position = {x:100,y:200} and save after it works !

My hypothesis :

May be my data.position have a prototype properties when I try to save it and the data cannot be saved. The problem is that I have no error and in the callback of the save function, the result var shown my application data...

note : I just see that it is not an official SchemaType (http://mongoosejs.com/docs/schematypes.html)...

My questions :

How to save correctly Object in document with mongoose ? Why I have no error if the save which failed ?

(I update to the last version 3.8.8 and I got the same issue).

Upvotes: 1

Views: 90

Answers (1)

Cyril ALFARO
Cyril ALFARO

Reputation: 1681

I got it : http://mongoosejs.com/docs/api.html#document_Document-markModified

In Mixed type (what my object type are) we need to specify to mongoose that they changed with the function bellow :

this.data.markModified('position');

Upvotes: 2

Related Questions