UNPKG

2.44 kBJavaScriptView Raw
1'use strict'
2
3var stringify = require('../stringify'),
4 check = require('../check')
5
6/**
7 * @class
8 * @property {string} collection
9 * @property {Obj} value
10 */
11function Find(collection, value) {
12 /** @member {string} */
13 this.collection = collection
14 /** @member {Obj} */
15 this.value = value
16}
17
18/**
19 * @param {Object} options
20 * @param {Object} options.db
21 * @param {Object} options.context
22 * @param {boolean} options.strict
23 * @param {string[]} options.ignoredFindKeys
24 * @param {Function} done
25 */
26Find.prototype.execute = function (options, done) {
27 var target = this.value.execute(options.context, '<find in ' + this.collection + '>'),
28 collection = options.db.collection(this.collection)
29
30 if ('_id' in target) {
31 this._executeWithId(target, collection, options, done)
32 } else {
33 this._executeWithoutId(target, collection, options, done)
34 }
35}
36
37Find.prototype._executeWithId = function (target, collection, options, done) {
38 var that = this
39 collection.findOne({
40 _id: target._id
41 }, function (err, doc) {
42 if (err) {
43 return done(err)
44 }
45
46 try {
47 check(doc, target, options.strict, options.ignoredFindKeys)
48 } catch (e) {
49 console.log('\n-----\n' +
50 '\x1b[1;32mDocument with id ' + target._id + ' in ' + that.collection + ':\x1b[0m\n' +
51 stringify(doc, true, e.path) + '\n' +
52 '\x1b[1;32mTarget document:\x1b[0m\n' +
53 stringify(target, true, e.path) + '\n' +
54 '-----\n')
55 return done(new Error('Document mismatch in ' + that.collection))
56 }
57
58 done()
59 })
60}
61
62Find.prototype._executeWithoutId = function (target, collection, options, done) {
63 var that = this
64 collection.find().toArray(function (err, docs) {
65 var errorPaths = [],
66 found
67
68 if (err) {
69 return done(err)
70 }
71
72 found = docs.some(function (doc) {
73 try {
74 check(doc, target, options.strict, options.ignoredFindKeys)
75 return true
76 } catch (e) {
77 errorPaths.push(e.path)
78 return false
79 }
80 })
81
82 if (!found) {
83 console.log('\n-----\n' +
84 '\x1b[1;32mDocuments in ' + that.collection + ':\x1b[0m\n' +
85 docs.map(function (doc, i) {
86 return stringify(doc, true, errorPaths[i])
87 }).join('\n---\n') + '\n' +
88 '\x1b[1;32mTarget document:\x1b[0m\n' +
89 stringify(target, true) + '\n' +
90 '-----\n')
91 return done(new Error('No document found in ' + that.collection))
92 }
93
94 done()
95 })
96}
97
98module.exports = Find
\No newline at end of file