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?