mongoose array push is not saving my entries and defying my simple wish to use push

Viewed 190

I have two schemas:

    var optionsSchema = new Schema({
    locationname: String,
    locationnumber : String     
});

var Xoption = mongoose.model('Xoption', optionsSchema);

var estoreSchema = new Schema({
    user: String,
    odds: String,
    //options: [optionsSchema]
    options: [{ type: Schema.Types.ObjectId, ref: 'Xoption' }]
});

var Estore = mongoose.model('Estore', estoreSchema);


export default Estore;
export {  Xoption };

Notice the options has [{type: Schema.Types.ObjectId, ref: 'Xoption'}] so it will store ids of objects from the xoptions collection.

Here is an example of one Estore document:

  {
        "_id" : ObjectId("5f998198df1e7b7598ba307c"),
        "options" : [
                ObjectId("5f998198df1e7b7598ba307b")
        ],
        "user" : "two",
        "odds" : "two",
        "__v" : 0
}

As you can see, options array contains ids for the Xoptions collection. Now when I try to push another id to the options array, I do the following: I get the id from the Xoption model. To simplify my code here and zoom on the relavant part of the question, I just assign it to a variable:

 let getid = 'ObjectId("5f997d78ace0547ba8c05646")';   

Now I need to push that id to options array in my Estore, so I do the following:

Estore.findOne({ "odds": "two" }).then(doc => {
    console.log("xxx", doc.options);
    doc.options.push(getid);

}).catch(err => {
    console.log("error message :", err);
});

When I do that, I get an error saying : error casting to ObjectId, and the err reason is:

    reason:
   Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

Now I'm getting somewhere, so I took the ObjectId out of the variable, I get no error but the id is not pushed to options array:

let getid = '5f997d78ace0547ba8c05646';

This is just a practice code. Copy it, change it, send me another example. just help me understand why a simple push operation to an array is not working.

My question: How do I push the value of that variable to the options array?

1 Answers

The issue was saving the model after I update it. so instead of this:

Estore.findOne({ "odds": "two" }).then(doc => {
console.log("xxx", doc.options);
doc.options.push(getid);

}).catch(err => {
    console.log("error message :", err);
});

Just add save after the push():

doc.save()

The complete code should be:

 Estore.findOne({ "odds": "two" }).then(doc => {
    console.log("xxx", doc.options);
   doc.options.push(getid);
    doc.save();
}).catch(err => {
   console.log("error message :", err);
});

Also, the options: [{ type: Schema.Types.ObjectId, ref: 'Xoption' }] accepts the ObjectId with 24bit characters, you don't need the ObjectId before, it should be like this:

let getid = '5f997d78ace0547ba8c05646';
Related