Class: Mongo::DB

Inherits:
Object show all
Includes:
WriteConcern
Defined in:
lib/mongo/db.rb

Overview

A MongoDB database.

Constant Summary collapse

SYSTEM_NAMESPACE_COLLECTION =
'system.namespaces'
SYSTEM_INDEX_COLLECTION =
'system.indexes'
SYSTEM_PROFILE_COLLECTION =
'system.profile'
SYSTEM_USER_COLLECTION =
'system.users'
SYSTEM_JS_COLLECTION =
'system.js'
SYSTEM_COMMAND_COLLECTION =
'$cmd'
PROFILE_LEVEL =
{
  :off       => 0,
  :slow_only => 1,
  :all       => 2
}
@@current_request_id =

Counter for generating unique request ids.

0

Instance Attribute Summary collapse

Attributes included from WriteConcern

#legacy_write_concern

Instance Method Summary collapse

Methods included from WriteConcern

#get_write_concern, gle?, #write_concern_from_legacy

Constructor Details

#initialize(name, client, opts = {}) ⇒ DB

Instances of DB are normally obtained by calling Mongo#db.

performed during a number of relevant operations. See DB#collection, DB#create_collection and DB#drop_collection.

Parameters:

  • name (String)

    the database name.

  • client (Mongo::MongoClient)

    a connection object pointing to MongoDB. Note that databases are usually instantiated via the MongoClient class. See the examples below.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :strict (Boolean) — default: False
    DEPRECATED

    If true, collections existence checks are

  • :pk (Object, #create_pk(doc)) — default: BSON::ObjectId

    A primary key factory object, which should take a hash and return a hash which merges the original hash with any primary key fields the factory wishes to inject. (NOTE: if the object already has a primary key, the factory should not inject a new key).

  • :w (String, Integer, Symbol) — default: 1

    Set default number of nodes to which a write should be acknowledged

  • :j (Boolean) — default: false

    Set journal acknowledgement

  • :wtimeout (Integer) — default: nil

    Set replica set acknowledgement timeout

  • :fsync (Boolean) — default: false

    Set fsync acknowledgement.

    Notes on write concern:

    These write concern options are propagated to Collection objects instantiated off of this DB. If no
    options are provided, the default write concern set on this instance's MongoClient object will be used. This
    default can be overridden upon instantiation of any collection by explicitly setting write concern options
    on initialization or at the time of an operation.
    
  • :cache_time (Integer) — default: 300

    Set the time that all ensure_index calls should cache the command.



90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/mongo/db.rb', line 90

def initialize(name, client, opts={})
  @name       = Mongo::Support.validate_db_name(name)
  @connection = client
  @strict     = opts[:strict]
  @pk_factory = opts[:pk]

  @write_concern = get_write_concern(opts, client)

  @read = opts[:read] || @connection.read
  Mongo::ReadPreference::validate(@read)
  @tag_sets = opts.fetch(:tag_sets, @connection.tag_sets)
  @acceptable_latency = opts.fetch(:acceptable_latency, @connection.acceptable_latency)
  @cache_time = opts[:cache_time] || 300 #5 minutes.
end

Instance Attribute Details

#acceptable_latencyObject

Read Preference



58
59
60
# File 'lib/mongo/db.rb', line 58

def acceptable_latency
  @acceptable_latency
end

#cache_timeObject

The length of time that Collection.ensure_index should cache index calls



55
56
57
# File 'lib/mongo/db.rb', line 55

def cache_time
  @cache_time
end

#connectionObject (readonly)

The Mongo::MongoClient instance connecting to the MongoDB server.



52
53
54
# File 'lib/mongo/db.rb', line 52

def connection
  @connection
end

#nameObject (readonly)

The name of the database and the local write concern options.



49
50
51
# File 'lib/mongo/db.rb', line 49

def name
  @name
end

#readObject

Read Preference



58
59
60
# File 'lib/mongo/db.rb', line 58

def read
  @read
end

#tag_setsObject

Read Preference



58
59
60
# File 'lib/mongo/db.rb', line 58

def tag_sets
  @tag_sets
end

#write_concernObject (readonly)

The name of the database and the local write concern options.



49
50
51
# File 'lib/mongo/db.rb', line 49

def write_concern
  @write_concern
end

Instance Method Details

#add_stored_function(function_name, code) ⇒ String

Adds a stored Javascript function to the database which can executed server-side in map_reduce, db.eval and $where clauses.

Parameters:

Returns:

  • (String)

    the function name saved to the database



161
162
163
164
165
166
167
168
# File 'lib/mongo/db.rb', line 161

def add_stored_function(function_name, code)
  self[SYSTEM_JS_COLLECTION].save(
    {
      "_id" => function_name,
      :value => BSON::Code.new(code)
    }
  )
end

#add_user(username, password, read_only = false) ⇒ Hash

Adds a user to this database for use with authentication. If the user already exists in the system, the password will be updated.

Parameters:

  • username (String)
  • password (String)
  • read_only (Boolean) (defaults to: false)

    Create a read-only user.

Returns:

  • (Hash)

    an object representing the user.



190
191
192
193
194
195
196
197
# File 'lib/mongo/db.rb', line 190

def add_user(username, password, read_only = false)
  users = self[SYSTEM_USER_COLLECTION]
  user  = users.find_one({:user => username}) || {:user => username}
  user['pwd'] = Mongo::Support.hash_password(username, password)
  user['readOnly'] = true if read_only;
  users.save(user)
  user
end

#authenticate(username, password, save_auth = true) ⇒ Boolean

Authenticate with the given username and password. Note that mongod must be started with the –auth option for authentication to be enabled.

Parameters:

  • username (String)
  • password (String)
  • save_auth (Boolean) (defaults to: true)

    Save this authentication to the client object using MongoClient#add_auth. This will ensure that the authentication will be applied on database reconnect. Note that this value must be true when using connection pooling.

Returns:

  • (Boolean)

Raises:



120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/mongo/db.rb', line 120

def authenticate(username, password, save_auth=true)
  if @connection.pool_size > 1 && !save_auth
    raise MongoArgumentError, "If using connection pooling, :save_auth must be set to true."
  end

  begin
    socket = @connection.checkout_reader(:primary_preferred)
    issue_authentication(username, password, save_auth, :socket => socket)
  ensure
    socket.checkin if socket
  end

  @connection.authenticate_pools
end

#collection(name, opts = {}) ⇒ Mongo::Collection Also known as: []

Get a collection by name.

Parameters:

  • name (String, Symbol)

    the collection name.

  • opts (Hash) (defaults to: {})

    any valid options that can be passed to Collection#new.

Returns:

Raises:

  • (MongoDBError)

    if collection does not already exist and we’re in strict mode.



314
315
316
317
318
319
320
321
322
# File 'lib/mongo/db.rb', line 314

def collection(name, opts={})
  if strict? && !collection_names.include?(name.to_s)
    raise MongoDBError, "Collection '#{name}' doesn't exist. (strict=true)"
  else
    opts = opts.dup
    opts.merge!(:pk => @pk_factory) unless opts[:pk]
    Collection.new(name, self, opts)
  end
end

#collection_namesArray

Get an array of collection names in this database.

Returns:

  • (Array)


237
238
239
240
241
# File 'lib/mongo/db.rb', line 237

def collection_names
  names = collections_info.collect { |doc| doc['name'] || '' }
  names = names.delete_if {|name| name.index(@name).nil? || name.index('$')}
  names.map {|name| name.sub(@name + '.', '')}
end

#collectionsArray<Mongo::Collection>

Get an array of Collection instances, one for each collection in this database.

Returns:



246
247
248
249
250
# File 'lib/mongo/db.rb', line 246

def collections
  collection_names.map do |name|
    Collection.new(name, self)
  end
end

#collections_info(coll_name = nil) ⇒ Mongo::Cursor

Get info on system namespaces (collections). This method returns a cursor which can be iterated over. For each collection, a hash will be yielded containing a ‘name’ string and, optionally, an ‘options’ hash.

Parameters:

  • coll_name (String) (defaults to: nil)

    return info for the specified collection only.

Returns:



259
260
261
262
263
# File 'lib/mongo/db.rb', line 259

def collections_info(coll_name=nil)
  selector = {}
  selector[:name] = full_collection_name(coll_name) if coll_name
  Cursor.new(Collection.new(SYSTEM_NAMESPACE_COLLECTION, self), :selector => selector)
end

#command(selector, opts = {}) ⇒ Hash

Send a command to the database.

Note: DB commands must start with the “command” key. For this reason, any selector containing more than one key must be an OrderedHash.

Note also that a command in MongoDB is just a kind of query that occurs on the system command collection ($cmd). Examine this method’s implementation to see how it works.

key, specifying the command to be performed. In Ruby 1.9, OrderedHash isn’t necessary since hashes are ordered by default.

Parameters:

  • selector (OrderedHash, Hash)

    an OrderedHash, or a standard Hash with just one

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :check_response (Boolean) — default: true

    If true, raises an exception if the command fails.

  • :socket (Socket)

    a socket to use for sending the command. This is mainly for internal use.

  • :read (:primary, :secondary)

    Read preference for this command. See Collection#find for more details.

  • :comment (String) — default: nil

    a comment to include in profiling logs

Returns:

Raises:



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
# File 'lib/mongo/db.rb', line 505

def command(selector, opts={})
  check_response = opts.fetch(:check_response, true)
  socket = opts[:socket]
  raise MongoArgumentError, "Command must be given a selector" unless selector.is_a?(Hash) && !selector.empty?

  if selector.keys.length > 1 && RUBY_VERSION < '1.9' && selector.class != BSON::OrderedHash
    raise MongoArgumentError, "DB#command requires an OrderedHash when hash contains multiple keys"
  end

  if read_pref = opts[:read]
    Mongo::ReadPreference::validate(read_pref)
    unless read_pref == :primary || Mongo::Support::secondary_ok?(selector)
      raise MongoArgumentError, "Command is not supported on secondaries: #{selector.keys.first}"
    end
  end

  begin
    result = Cursor.new(
      system_command_collection,
      :limit => -1,
      :selector => selector,
      :socket => socket,
      :read => read_pref,
      :comment => opts[:comment]).next_document
  rescue OperationFailure => ex
    raise OperationFailure, "Database command '#{selector.keys.first}' failed: #{ex.message}"
  end

  raise OperationFailure,
    "Database command '#{selector.keys.first}' failed: returned null." unless result

  if check_response && !ok?(result)
    message = "Database command '#{selector.keys.first}' failed: ("
    message << result.map do |key, value|
      "#{key}: '#{value}'"
    end.join('; ')
    message << ').'
    code = result['code'] || result['assertionCode']
    raise OperationFailure.new(message, code, result)
  end

  result
end

#create_collection(name, opts = {}) ⇒ Mongo::Collection

Create a collection.

new collection. If strict is true, will raise an error if collection name already exists.

Parameters:

  • name (String, Symbol)

    the name of the new collection.

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :capped (Boolean) — default: False

    created a capped collection.

  • :size (Integer) — default: Nil

    If capped is true, specifies the maximum number of bytes for the capped collection. If false, specifies the number of bytes allocated for the initial extent of the collection.

  • :max (Integer) — default: Nil

    If capped is true, indicates the maximum number of records in a capped collection.

Returns:

Raises:

  • (MongoDBError)

    raised under two conditions: either we’re in strict mode and the collection already exists or collection creation fails on the server.



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/mongo/db.rb', line 287

def create_collection(name, opts={})
  name = name.to_s
  if strict? && collection_names.include?(name)
    raise MongoDBError, "Collection '#{name}' already exists. (strict=true)"
  end

  begin
    cmd = BSON::OrderedHash.new
    cmd[:create] = name
    doc = command(cmd.merge(opts || {}))
    return Collection.new(name, self, :pk => @pk_factory) if ok?(doc)
  rescue OperationFailure => e
    return Collection.new(name, self, :pk => @pk_factory) if e.message =~ /exists/
    raise e
  end
  raise MongoDBError, "Error creating collection: #{doc.inspect}"
end

#dereference(dbref) ⇒ Hash

Dereference a DBRef, returning the document it points to.

Parameters:

  • dbref (Mongo::DBRef)

Returns:

  • (Hash)

    the document indicated by the db reference.

See Also:



394
395
396
# File 'lib/mongo/db.rb', line 394

def dereference(dbref)
  collection(dbref.namespace).find_one("_id" => dbref.object_id)
end

#drop_collection(name) ⇒ Boolean

Drop a collection by name.

Parameters:

Returns:

  • (Boolean)

    true on success or false if the collection name doesn’t exist.



330
331
332
333
334
335
336
337
# File 'lib/mongo/db.rb', line 330

def drop_collection(name)
  return false if strict? && !collection_names.include?(name.to_s)
  begin
    ok?(command(:drop => name))
  rescue OperationFailure => e
    false
  end
end

#drop_index(collection_name, index_name) ⇒ True

Drop an index from a given collection. Normally called from Collection#drop_index or Collection#drop_indexes.

Parameters:

Returns:

  • (True)

    returns true on success.

Raises:

  • MongoDBError if there’s an error dropping the index.



442
443
444
445
446
447
448
# File 'lib/mongo/db.rb', line 442

def drop_index(collection_name, index_name)
  cmd = BSON::OrderedHash.new
  cmd[:deleteIndexes] = collection_name
  cmd[:index] = index_name.to_s
  doc = command(cmd, :check_response => false)
  ok?(doc) || raise(MongoDBError, "Error with drop_index command: #{doc.inspect}")
end

#error?Boolean

Return true if an error was caused by the most recently executed database operation.

Returns:

  • (Boolean)


362
363
364
# File 'lib/mongo/db.rb', line 362

def error?
  get_last_error['err'] != nil
end

#eval(code, *args) ⇒ String

Evaluate a JavaScript expression in MongoDB.

Parameters:

  • code (String, Code)

    a JavaScript expression to evaluate server-side.

  • args (Integer, Hash)

    any additional argument to be passed to the code expression when it’s run on the server.

Returns:

  • (String)

    the return value of the function.



405
406
407
408
409
410
411
412
413
414
415
# File 'lib/mongo/db.rb', line 405

def eval(code, *args)
  unless code.is_a?(BSON::Code)
    code = BSON::Code.new(code)
  end

  cmd = BSON::OrderedHash.new
  cmd[:$eval] = code
  cmd[:args] = args
  doc = command(cmd)
  doc['retval']
end

#full_collection_name(collection_name) ⇒ String

A shortcut returning db plus dot plus collection name.

Parameters:

Returns:



554
555
556
# File 'lib/mongo/db.rb', line 554

def full_collection_name(collection_name)
  "#{@name}.#{collection_name}"
end

#get_last_error(opts = {}) ⇒ Hash

Run the getlasterror command with the specified replication options.

Parameters:

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :fsync (Boolean) — default: false
  • :w (Integer) — default: nil
  • :wtimeout (Integer) — default: nil
  • :j (Boolean) — default: false

Returns:

  • (Hash)

    the entire response to getlasterror.

Raises:



349
350
351
352
353
354
355
356
# File 'lib/mongo/db.rb', line 349

def get_last_error(opts={})
  cmd = BSON::OrderedHash.new
  cmd[:getlasterror] = 1
  cmd.merge!(opts)
  doc = command(cmd, :check_response => false)
  raise MongoDBError, "Error retrieving last error: #{doc.inspect}" unless ok?(doc)
  doc
end

#index_information(collection_name) ⇒ Hash

Get information on the indexes for the given collection. Normally called by Collection#index_information.

Parameters:

Returns:

  • (Hash)

    keys are index names and the values are lists of [key, type] pairs defining the index.



457
458
459
460
461
462
463
464
# File 'lib/mongo/db.rb', line 457

def index_information(collection_name)
  sel  = {:ns => full_collection_name(collection_name)}
  info = {}
  Cursor.new(Collection.new(SYSTEM_INDEX_COLLECTION, self), :selector => sel).each do |index|
    info[index['name']] = index
  end
  info
end

#issue_authentication(username, password, save_auth = true, opts = {}) ⇒ Object

Raises:



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/mongo/db.rb', line 135

def issue_authentication(username, password, save_auth=true, opts={})
  doc = command({:getnonce => 1}, :check_response => false, :socket => opts[:socket])
  raise MongoDBError, "Error retrieving nonce: #{doc}" unless ok?(doc)
  nonce = doc['nonce']

  auth = BSON::OrderedHash.new
  auth['authenticate'] = 1
  auth['user'] = username
  auth['nonce'] = nonce
  auth['key'] = Mongo::Support.auth_key(username, password, nonce)
  if ok?(doc = self.command(auth, :check_response => false, :socket => opts[:socket]))
    @connection.add_auth(@name, username, password) if save_auth
  else
    message = "Failed to authenticate user '#{username}' on db '#{self.name}'"
    raise Mongo::AuthenticationError.new(message, doc['code'], doc)
  end
  true
end

#issue_logout(opts = {}) ⇒ Object



225
226
227
228
229
230
231
232
# File 'lib/mongo/db.rb', line 225

def issue_logout(opts={})
  if ok?(doc = command({:logout => 1}, :socket => opts[:socket]))
    @connection.remove_auth(@name)
  else
    raise MongoDBError, "Error logging out: #{doc.inspect}"
  end
  true
end

#logout(opts = {}) ⇒ Boolean

Deauthorizes use for this database for this client connection. Also removes any saved authentication in the MongoClient class associated with this database.

Returns:

  • (Boolean)

Raises:



220
221
222
223
# File 'lib/mongo/db.rb', line 220

def logout(opts={})
  @connection.logout_pools(@name) if @connection.pool_size > 1
  issue_logout(opts)
end

#ok?(doc) ⇒ Boolean

Return true if the supplied doc contains an ‘ok’ field with the value 1.

Parameters:

Returns:

  • (Boolean)


478
479
480
# File 'lib/mongo/db.rb', line 478

def ok?(doc)
  Mongo::Support.ok?(doc)
end

#pk_factoryObject, Nil

The primary key factory object (or nil).

Returns:



561
562
563
# File 'lib/mongo/db.rb', line 561

def pk_factory
  @pk_factory
end

#pk_factory=(pk_factory) ⇒ Object

Specify a primary key factory if not already set.

Raises:



568
569
570
571
572
573
# File 'lib/mongo/db.rb', line 568

def pk_factory=(pk_factory)
  raise MongoArgumentError,
    "Cannot change primary key factory once it's been set" if @pk_factory

  @pk_factory = pk_factory
end

#previous_errorString, Nil

Get the most recent error to have occurred on this database.

This command only returns errors that have occurred since the last call to DB#reset_error_history - returns nil if there is no such error.

Returns:

  • (String, Nil)

    the text of the error or nil if no error has occurred.



372
373
374
375
# File 'lib/mongo/db.rb', line 372

def previous_error
  error = command(:getpreverror => 1)
  error["err"] ? error : nil
end

#profiling_infoArray

Get the current profiling information.

Returns:

  • (Array)

    a list of documents containing profiling information.



607
608
609
# File 'lib/mongo/db.rb', line 607

def profiling_info
  Cursor.new(Collection.new(SYSTEM_PROFILE_COLLECTION, self), :selector => {}).to_a
end

#profiling_levelSymbol

Return the current database profiling level. If profiling is enabled, you can get the results using DB#profiling_info.

Returns:

  • (Symbol)

    :off, :slow_only, or :all



581
582
583
584
585
586
587
588
589
590
591
# File 'lib/mongo/db.rb', line 581

def profiling_level
  cmd = BSON::OrderedHash.new
  cmd[:profile] = -1
  doc = command(cmd, :check_response => false)

  raise "Error with profile command: #{doc.inspect}" unless ok?(doc)

  level_sym = PROFILE_LEVEL.invert[doc['was'].to_i]
  raise "Error: illegal profiling level value #{doc['was']}" unless level_sym
  level_sym
end

#profiling_level=(level) ⇒ Object

Set this database’s profiling level. If profiling is enabled, you can get the results using DB#profiling_info.

Parameters:

  • level (Symbol)

    acceptable options are :off, :slow_only, or :all.



597
598
599
600
601
602
# File 'lib/mongo/db.rb', line 597

def profiling_level=(level)
  cmd = BSON::OrderedHash.new
  cmd[:profile] = PROFILE_LEVEL[level]
  doc = command(cmd, :check_response => false)
  ok?(doc) || raise(MongoDBError, "Error with profile command: #{doc.inspect}")
end

#remove_stored_function(function_name) ⇒ Boolean

Removes stored Javascript function from the database. Returns false if the function does not exist

Parameters:

Returns:

  • (Boolean)


176
177
178
179
# File 'lib/mongo/db.rb', line 176

def remove_stored_function(function_name)
  return false unless self[SYSTEM_JS_COLLECTION].find_one({"_id" => function_name})
  self[SYSTEM_JS_COLLECTION].remove({"_id" => function_name}, :w => 1)
end

#remove_user(username) ⇒ Boolean

Remove the given user from this database. Returns false if the user doesn’t exist in the system.

Parameters:

Returns:

  • (Boolean)


205
206
207
208
209
210
211
# File 'lib/mongo/db.rb', line 205

def remove_user(username)
  if self[SYSTEM_USER_COLLECTION].find_one({:user => username})
    self[SYSTEM_USER_COLLECTION].remove({:user => username}, :w => 1)
  else
    false
  end
end

#rename_collection(from, to) ⇒ True

Rename a collection.

Parameters:

  • from (String)

    original collection name.

  • to (String)

    new collection name.

Returns:

  • (True)

    returns true on success.

Raises:

  • MongoDBError if there’s an error renaming the collection.



425
426
427
428
429
430
431
# File 'lib/mongo/db.rb', line 425

def rename_collection(from, to)
  cmd = BSON::OrderedHash.new
  cmd[:renameCollection] = "#{@name}.#{from}"
  cmd[:to] = "#{@name}.#{to}"
  doc = DB.new('admin', @connection).command(cmd, :check_response => false)
  ok?(doc) || raise(MongoDBError, "Error renaming collection: #{doc.inspect}")
end

#reset_error_historyHash

Reset the error history of this database

Calls to DB#previous_error will only return errors that have occurred since the most recent call to this method.

Returns:



383
384
385
# File 'lib/mongo/db.rb', line 383

def reset_error_history
  command(:reseterror => 1)
end

#statsHash

Return stats on this database. Uses MongoDB’s dbstats command.

Returns:



469
470
471
# File 'lib/mongo/db.rb', line 469

def stats
  self.command({:dbstats => 1})
end

#strict=(value) ⇒ Object

Deprecated.

Support for strict will be removed in version 2.0 of the driver.

Strict mode enforces collection existence checks. When true, asking for a collection that does not exist, or trying to create a collection that already exists, raises an error.

Strict mode is disabled by default, but enabled (true) at any time.



33
34
35
36
37
38
39
# File 'lib/mongo/db.rb', line 33

def strict=(value)
  unless ENV['TEST_MODE']
    warn "Support for strict mode has been deprecated and will be " +
         "removed in version 2.0 of the driver."
  end
  @strict = value
end

#strict?Boolean

Deprecated.

Support for strict will be removed in version 2.0 of the driver.

Returns the value of the strict flag.

Returns:

  • (Boolean)


44
45
46
# File 'lib/mongo/db.rb', line 44

def strict?
  @strict
end

#validate_collection(name) ⇒ Hash

Validate a named collection.

Parameters:

  • name (String)

    the collection name.

Returns:

  • (Hash)

    validation information.

Raises:

  • (MongoDBError)

    if the command fails or there’s a problem with the validation data, or if the collection is invalid.



619
620
621
622
623
624
625
626
627
628
629
630
631
# File 'lib/mongo/db.rb', line 619

def validate_collection(name)
  cmd = BSON::OrderedHash.new
  cmd[:validate] = name
  cmd[:full] = true
  doc = command(cmd, :check_response => false)

  raise MongoDBError, "Error with validate command: #{doc.inspect}" unless ok?(doc)

  if (doc.has_key?('valid') && !doc['valid']) || (doc['result'] =~ /\b(exception|corrupt)\b/i)
    raise MongoDBError, "Error: invalid collection #{name}: #{doc.inspect}"
  end
  doc
end