I am trying to save an array of objects in a document using mongoose. I tried several times but did not save the array in the document. It puts an empty array into the document.
Below is my diagram:
var ProfileSchema = new Schema({ name: String, PagesData: [{ pageAccessToken: {type: String, get: decryptText, set: encryptText}, category: String, name: String, id: String, perms: [String] }] }); module.exports = mongoose.model('Profile', ProfileSchema);
I am trying to save a document with an array of objects using the following query:
var newProfile = new Profile(); newProfile.name = "someName"; newProfile.PagesData = [ { pageAccessToken: 'someToken', category: 'Bags/Luggage', name: 'someBrandName', id: '12345', perms: [ 'ADMINISTER', 'EDIT_PROFILE', 'CREATE_CONTENT' ] } ]; newProfile.save(function(err, result, numAffected){ if(err) { console.log(err); res.send(500, "Error"); } console.log(result); res.send(200, "Success"); });
I tried debugging mongo commands with
require ('mongoose'). set ('debug', true)
Debug logs display an empty array during the execution of an insert command.
Can anyone tell me how I can save this array of object in my schema?
Thanks,
Update:
It has been too long, and I still cannot understand the root cause of the problem. There is a long thread for github for this. https://github.com/Automattic/mongoose/issues/3249 I would like other experts to catch the eye and offer me some way with which I can solve this problem. I am really stuck with this.
Update 2:
None of the solutions have worked for me so far, so I decided to change the scheme only to meet my requirements. This led to another problem:
I want to create a map with the objectId key and an array of string values ββas the value. The closest I can get is:
var schema = new Schema({ map: [{myId: {type:mongoose.Schema.Types.ObjectId, ref: 'MyOtherCollection'}, values: [String]}] });
But for some reason this does not work for me. When I update using {upsert: true}, it fails to populate the key value: on the map. In fact, I'm not even sure if I declared the schema correctly.
Can someone tell me if the circuit is correct? Also, how can I upgrade using {upsert: true} for this schema?
In addition, if the above is incorrect and can be achieved, then how can I simulate my requirement in some other way. My use case I want to keep a list of values ββfor this object. I do not want duplicate records with a single key, so I chose a map.
Please propose whether this approach is correct or should it be modeled in some other way?
thanks