【问题标题】:Node.js: update mongoDB document using mongoose.jsNode.js:使用 mongoose.js 更新 mongoDB 文档
【发布时间】:2014-02-26 11:31:58
【问题描述】:

我已经定义了这个架构:

var bookCollection = new mongoose.Schema({

    book:[{
        bookTitle: String,
        bookOrder: Number,
        bookChapters: [{
            chapterTitle: String,
            chapterIntro: String,
            chapterOrder: Number,
            chapterArticles: [{
                articleTitle: String,
                articleIntro: String,
                articleOrder: Number,
                articleHeadings: [{
                    headingTitle: String,
                    headingOrder: Number
                }]
            }]
        }]
    }]


});

var bookModel = mongoose.model('bookModel', bookCollection);

然后我将 1 个文档保存到 mongoDB,这是使用 db.bookmodels.find() 检查时的 JSON 对象

{
"_id": ObjectId("530cc92710f774355434b394"),
"book": [
    {
        "bookTitle": "Javascript",
        "bookOrder": 300,
        "_id": ObjectId("530cc92710f774355434b395"),
        "bookChapters": [
            {
                "chapterTitle": "Functions",
                "chapterIntro": "All about javascript functions",
                "chapterOrder": 500,
                "_id": ObjectId("530cc92710f774355434b396"),
                "chapterArticles": [
                    {
                        "articleTitle": "A visual illustration of the JS function",
                        "articleIntro": "Something to see here, check it out",
                        "articleOrder": 500,
                        "_id": ObjectId("530cc92710f774355434b397"),
                        "articleHeadings": [
                            {
                                "headingTitle": "Parts of a function",
                                "headingOrder": 500,
                                "_id": ObjectId("530cc92710f774355434b398")
                            }
                        ]
                    }
                ]
            }
        ]
    }
],
"__v": 0

}

如果我想将 headingOrder 更改为 100 而不是 500,我将如何使用 mongoose.js 更新数据库?我一直在尝试几件事,但我似乎无法理解它。

在任何地方,您都会看到具有简单架构的示例,但从未像这样使用复杂架构的示例。

谢谢。

【问题讨论】:

  • 您是要更新每本书的all articleHeadings、本书(或本书的章节)中的所有articleHeadings 中的值,还是只更新这一本书, articleHeading 带有_id 530cc92710f774355434b398?
  • 做不到。不是我能看到的 - 无论如何都不是在一个查询中。我认为您需要重新考虑架构。 mongodb 的原则之一是为您的访问模式设计架构。
  • 有没有关于 mongoose 中良好架构设计的资源(文章)?

标签: javascript node.js mongodb mongoose


【解决方案1】:

您始终可以将文档加载到内存中,进行修改,即book[0].bookChapters[0].chapterArticles[0].articleHeadings[0].headingOrder = 100 然后save() 它。

上面链接中的示例正是这样做的,document.find() 后跟 save()

【讨论】:

  • 这是正常的做事方式吗,看起来相当复杂冗长?
  • 您还能如何将该特定字段与 book[1].bookChapters[3].chapterArticles[2].articleHeadings[16].headingTitle 等其他字段区分开来?
猜你喜欢
  • 2014-10-31
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 2011-12-04
  • 2017-06-21
  • 2018-04-18
相关资源
最近更新 更多