如何通过 Mongoose Node.js ORM 更新 MongoDB 文档中的嵌套对象字段?
我不知道如何通过 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
仍然具有其原始值,尽管保存时没有错误()
。
我怀疑我需要以不同的方式引用content
...但是如何呢?谢谢!
编辑:如果我做这样的事情,它会起作用:
for page in article.pages
if page is whatever
page.content = 'foo'
article.save()
但是,这看起来相当不优雅且效率低下。
I can't figure out how to change the value of a field in a nested document in a MongoDB document via the Mongoose Node.js JavaScript ORM. Code in 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()
)
The next time I fetch article
, article.pages[0].content
still has its original value, although there is no error on the save()
.
I suspect I need to reference content
differently... but how? Thanks!
Edit: It works if I do something like this:
for page in article.pages
if page is whatever
page.content = 'foo'
article.save()
However, that seems pretty inelegant and inefficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用
update
函数。You have to use the
update
function.