【问题标题】:How to update in mongoose?如何在猫鼬中更新?
【发布时间】:2012-05-18 23:10:11
【问题描述】:

我是 Mongoose/nodejs 的新手,我正在努力对数组中的数组进行简单更新。

这是架构:

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"},
});

这是我一直在尝试的更新代码:

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

执行此操作时,err 中的错误为“无法使用字符串字段名称 'counties' 附加到数组”。这是什么意思?我做错了什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您应该将子对象定义为另一个 Schema,而不仅仅是一些匿名对象的列表。 (Reference.)

    尝试将Country 定义为单独的架构,将其嵌套在Continent 中,然后进行更新。

    【讨论】:

    • 好的。是否没有任何替代方法来更新嵌套数组,而无需重新定义架构?
    • @tremolo:可能有也可能没有(我的 Mongoose-fu 仍然很弱),但我认为无论如何为Country 定义一个模式是一个好习惯。
    • 已解决! update 参数应该只将要更新的属性指定为“name”而不是“countries.counties.name”。
    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2017-05-20
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2022-12-22
    相关资源
    最近更新 更多