How to update in mongoose?

I am new to Mongoose / nodejs and I am struggling with simple updating an array in an array.

Here's the diagram:

var County = new Schema({ _id : Schema.ObjectId, name : String, biggestCity : String }); var Country = new Schema({ _id : Schema.ObjectId, name : String, counties : {type: [County], ref: "County"} }); var Continent = new Schema({ _id : Schema.ObjectId, countries : {type: [Country], ref: "Country"}, }); 

And here is the update code I tried:

 var continents = mongoose.model("Continent"); var update = { "countries.counties.name": newName, "countries.counties.biggestCity": newBiggestCity }; var conditions = { "_id": countryId, "countries.name": countryName, "countries.counties.name": countyName }; var options = { multi: false }; wagers.update(conditions, update, options, function(err, numAffected) { //callback code... }); 

The err error says: “Cannot add the array using the field name“ counties. ”What does this mean? What am I doing wrong?

+6
source share
1 answer

You must define the child object as a different scheme, and not just as a list of some anonymous objects. ( Link .)

Try defining Country as a separate schema nested in Continent , then upgrade.

+1
source

Source: https://habr.com/ru/post/915388/


All Articles