user1379417
user1379417

Reputation:

How to update in mongoose?

I am new at Mongoose/nodejs and I am struggling with a simple update of an array within an array.

Here's the schema:

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's the update code I've been trying:

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...
});

When doing this, the error in err says "Can't append to array using string field name 'counties'". What does this mean? What am I doing wrong?

Upvotes: 6

Views: 3164

Answers (1)

Asherah
Asherah

Reputation: 19347

You should define the child object as another Schema, not just as a list of some anonymous object. (Reference.)

Try defining Country as a separate Schema, nest that in Continent, then do your update.

Upvotes: 1

Related Questions