Shamoon
Shamoon

Reputation: 43559

$pull won't work when updating with MongooseJS in Node.js

query =
  _id: mongoose.Types.ObjectId fan_id
  'fanclubs.fanclub_id': fanclub_id

removeSubDoc =
  '$pull':
    fanclubs:
      fanclub_id: fanclub_id

updOptions =
  multi: true

Fan.update query, removeSubDoc, updOptions, (err, cnt) ->

That's my code. I've hardcoded things to make sure that the documents in question are there. but this doesn't seem to pull the subobject:

{
  "_id" : ObjectId( "5075dc3323863bca2e00000a" ),
  "added_on" : Date( 1349901363053 ),
  "address" : { "country" : "0",
    "zip" : "07006",
    "state" : "0",
    "city" : "Caldwell",
    "address" : null },
  "birth_date" : Date( 646632000000 ),
  "city" : "Caldwell",
  "country" : "0",
  "email" : "[email protected]",
  "events" : [],
  "fanclubs" : [ 
    { "fanclub_id" : "50b26eb5b62ac1cc0a000006",
      "fanclub_name" : "Vitamin Water",
      "fanclub_image" : "https://s3.amazonaws.com/fanclubs/5f129d8d6af3a8ae0b17cc8d2f7e5a30.png",
      "access" : "client",
      "_id" : ObjectId( "50b26eb5b62ac1cc0a000008" ),
      "joinedOn" : Date( 1353871029377 ) } ],
  "first_name" : "Admin",
  "fullname" : "Admin Istrator",
  "gender" : "male",
  "last_name" : "Istrator",
  "password" : "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
  "phone" : "(862) 298-1898",
  "state" : "0",
  "status" : "active",
  "user_type" : "admin",
  "zip" : "07067" }

My Fan Schema:

FanSchema = new mongoose.Schema(
  first_name:
    type: String
    trim: true
    required: true
  fanclubs:
    type: [FanClubMemberSchema]
    required: false

and.. 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

Upvotes: 0

Views: 318

Answers (1)

randunel
randunel

Reputation: 8945

When using Mongoose queries, always use ObjectId.toString(). It's safe to use toString even with strings.

Try:

query =
    _id: fan_id.toString()
        'fanclubs.fanclub_id': fanclub_id.toString()

removeSubDoc =
    '$pull':
        fanclubs:
            fanclub_id: fanclub_id.toString()

Upvotes: 1

Related Questions