使用Mongoose更新子文档

时间:2012-11-07 16:21:38

标签: node.js mongodb coffeescript mongoose

好的,所以我正在尝试使用Mongoose更新子文档(嵌入文档)。我有:

    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

似乎没有使用新Fan实际更新fanclub_name对象。想法?

我想更新fanclub_name字段

编辑我的Fan架构

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

1 个答案:

答案 0 :(得分:3)

默认情况下,update操作只会更新它匹配的第一个文档。因此,这只会更新包含fanclubs的第一个粉丝的fanclub_id数据。所以我认为它可能有效,但你没有检查更新的fan文档。

要更新所有粉丝的数据,您需要启用multi选项:

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