Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Updating subdocuments with Mongoose

Updating subdocuments with Mongoose

Problem

Okay, so I'm trying to update a subdocument (embedded document) with Mongoose. I have:

    query =
      'fanclubs.fanclub_id': fanclub_id

    fan_update =
      'fanclubs.$.fanclub_name': fanclub_data.fanclub_name

    Fan.update query, fan_update, (err, numAffected) ->
      console.log err
      console.log numAffected

Doesn't seem to actually update the Fan object with the new fanclub_name. Ideas?

I want to update the fanclub_name field

EDIT My Fan Schema

mongoose = require "mongoose"
{FanClubMemberSchema} = require './schemas/fanClubMemberSchema'
validation = require './validation'

FanSchema = new mongoose.Schema(
  first_name:
    type: String
    trim: true
    required: true

  last_name:
    type: String
    trim: true
    required: true

  fullname:
    type: String
    trim: true
    required: true

  email:
    type: String
    lowercase: true
    unique: true
    required: true
    validate: [validation.email, 'Email is invalid']

  fanclubs:
    type: [FanClubMemberSchema]
    required: false

  added_on:
    type: Date
    default: Date.now
    required: true
)

FanClubMemberSchema

mongoose = require "mongoose"

FanClubMemberSchema = new mongoose.Schema
  fanclub_id:
    type:  String
    trim:  true
    required: true

  fanclub_name:
    type: String
    trim: true
    required: true

  fanclub_image:
    type: String
    trim:true
    required:true

  access:
    type:  String
    trim:  true
    required: true

  joinedOn:
    type:  Date
    default: Date.now
    required: true    

exports.FanClubMemberSchema = FanClubMemberSchema
Problem courtesy of: Shamoon

Solution

By default, an update operation will only update the first document it matches. So this will only update the first fan's fanclubs data where it contains fanclub_id. So I'm thinking it's probably working, but you're not checking the one fan document that was updated.

To update all fans' data you need to enable the multi option:

Fan.update query, fan_update, { multi: true }, (err, numAffected) ->
  console.log err
  console.log numAffected
Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Updating subdocuments with Mongoose

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×