mrjf
mrjf

Reputation: 1137

How to update nested object field in MongoDB document via Mongoose Node.js ORM?

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.

Upvotes: 0

Views: 3643

Answers (1)

rafalio
rafalio

Reputation: 3946

You have to use the update function.

Upvotes: 3

Related Questions