【问题标题】:How to update nested object field in MongoDB document via Mongoose Node.js ORM?如何通过 Mongoose Node.js ORM 更新 MongoDB 文档中的嵌套对象字段?
【发布时间】:2011-10-17 22:23:04
【问题描述】:

我不知道如何通过 Mongoose Node.js JavaScript ORM 更改 MongoDB 文档中嵌套文档中字段的值。 CoffeeScript 中的代码:

mongoose = require 'mongoose'
mongoose.connect 'mongodb://localhost/test'
Schema = mongoose.Schema

Page = new Schema
  content: String

Article = new Schema
  _id: String
  pages: [Page] 

article_model = mongoose.model 'Article', Article, 'testcollection'

article_model.findOne({_id: 'id1'}, (err, article) =>
  article.pages[0].content = 'foo'
  article.save()
)

下次取article时,article.pages[0].content还是有原来的值,虽然save()没有报错。

我怀疑我需要以不同的方式引用content...但是如何?谢谢!

编辑:如果我这样做,它会起作用:

for page in article.pages
  if page is whatever
    page.content = 'foo'
article.save()

但是,这似乎很不优雅且效率低下。

【问题讨论】:

    标签: mongodb node.js coffeescript mongoose


    【解决方案1】:

    你必须使用update函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-04
      • 2021-02-13
      • 2017-04-01
      • 2020-03-17
      • 2021-03-26
      • 2020-03-14
      • 1970-01-01
      • 2015-01-31
      相关资源
      最近更新 更多