嵌套文档上的猫鼬$ inc操作错误

时间:2019-06-06 06:08:35

标签: javascript mongoose mongoose-schema

我有以下架构:

const postsStatsSchema = new Schema({
    postid: {
        type: String,
        maxlength: [128, "post ID must be at most 128"],
        required: true
    },
    likecounter: {
        type: Number,
        default: 0,
        min: 0,
        required: true
    }
});

const userStatsSchema = new Schema({
    username: {
        type: String,
        required: true,
        maxlength: [50, "Name length must be at most 50"]
    },
    posts: {
        type: [postsStatsSchema],
        required: true
    }
});

const statisticsSchema = new Schema({
    month: {
        type: Number,
        required: true
    },
    users: {
        type: [userStatsSchema],
        required: true
    }
}, {
    timestamps: true
});

我正在尝试增加(或创建,如果文档不存在)postsStats对象中的“ likecounter”。我尝试了许多不同的方法,但没有成功。这是我尝试过的最后一件事:

let update = {};
update['$inc'] = {};
update['$inc'] = {'users.$.username.user.$.posts.somepost.likecounter': 1000};

try {
    const res = await stats.findOneAndUpdate({month: 100}, update, {'upsert': true});
    console.log(res);
} catch (err) {
    console.log(err);
}

我在上面的代码中遇到的错误是:

 MongoError: Too many positional (i.e. '$') elements found in path

我尝试了多种变体,带有和不带有“ $”符号,但仅设法增加了月份。我相信我在嵌套文档中做错了事,但只是弄不清楚是什么。

0 个答案:

没有答案