dispatch:bound-document

v0.0.2Published 10 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

dispatch:bound-document

A Meteor package that adds a {bind: true} option to MongoDB and MiniMongo document fetches. When you use it, the returned doc is a BoundDocument instance, which will update the database when you set its properties.

  • Works on all collection types, managed or unmanaged, local or remote
  • Works in both client and server code
  • Works on deeply nested properties, but not within arrays

Installation

$ meteor add dispatch:bound-document

Prerequisites

The bind option will only work if you have attached a SimpleSchema to your collection. See https://github.com/aldeed/meteor-collection2.

Functions That Support Binding

  • cursor.fetch
  • cursor.forEach
  • cursor.map
  • collection.findOne

Examples

Basic

1// Initialize the collection and attach a schema
2var c = new Mongo.Collection('widgets');
3c.attachSchema({name: {type: String}});
4
5// Insert a document
6c.insert({_id: '1', name: 'foo'});
7
8// Retrieve the document with `bind` option set to `true`
9var doc = c.findOne('1', {bind: true});
10
11console.log(doc.name); // foo
12
13// Now we just set the property. This changes the property value not only in the
14// object but also in the database (or local collection).
15doc.name = 'bar';
16
17console.log(doc.name); // bar
18doc = c.findOne('1');
19console.log(doc.name); // still bar

Nested

1// Initialize the collection and attach a schema
2var c = new Mongo.Collection('widgets');
3c.attachSchema({
4  name: {type: String},
5  one: {
6    type: Object,
7    optional: true
8  },
9  'one.two': {
10    type: Object,
11    optional: true
12  },
13  'one.two.three': {
14    type: String,
15    optional: true
16  }
17});
18
19// Insert a document
20c.insert({_id: '1', name: 'foo'});
21
22// Retrieve the document with `bind` option set to `true`
23var doc = c.findOne('1', {bind: true});
24
25// Even though there is no `one` property, we can do `doc.one.two.three`
26// without fear of error. All possible object fields are initialized.
27console.log(doc.one.two.three); // undefined
28
29// Now we just set the property. This changes the property value not only in the
30// object but also in the database (or local collection).
31doc.one.two.three = 'bar';
32
33console.log(doc.one.two.three); // bar
34doc = c.findOne('1');
35console.log(doc.one.two.three); // still bar

Binding A Document

You don't have to rely findOne, fetch, etc. to bind a document for you. You can bind a document at any time after retrieving it, in client or server code:

1var boundDoc = new BoundDocument(AnyCollectionWithASchemaAttached, normalDoc);