在Node.js中使用MongooseJS进行更新时,$ pull将不起作用

时间:2012-11-25 20:17:20

标签: node.js mongodb mongoose

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) ->

这是我的代码。我已经硬编码以确保有问题的文件存在。但这似乎没有拉出子对象:

{
  "_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" : "admin@gmail.com",
  "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" }

我的Fan架构:

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

和.. 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 :(得分:1)

使用Mongoose查询时,请始终使用ObjectId.toString()。即使使用字符串也可以使用toString。

尝试:

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

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