## Model Data Functions 
### Find One
@extends ghostBookshelf.Model.findOne to handle post status
**See:** [ghostBookshelf.Model.findOne](base.js.html#Find%20One)
519069
function findOne(data = {}, options = {}) {
        // @TODO: remove when we drop v0.1
        if (!options.filter && !data.status) {
            data.status = 'published';
        }

        if (data.status === 'all') {
            delete data.status;
        }

        return ghostBookshelf.Model.findOne.call(this, data, options);
    }
1224906
function(res, method, model, options) {
		// parse non-document responses
		if (res._id == null && res._rev == null) {
			// write result
			if (method !== "read") return { _id: res.id, _rev: res.rev };

			// view result
			if (res.rows != null) {
				if (isCollection(model)) return res.rows.map(function(row) {
					return row[options.rowKey];
				});

				// grab just the first row for models
				return res.rows.length ? res.rows[0][options.rowKey] : null;
			}

			// changes feed result
			if (res[options.rowKey] != null) return res[options.rowKey];
		}

		return res;
	}
156565
function modelQuery(options) {
            return models.Post.findPage(options)
                .then(({data, meta}) => {
                    return {
                        posts: data.map(model => urlsForPost(model.id, model.toJSON(options), options)),
                        meta: meta
                    };
                });
        }
1351992
function ( req, model ) {
		// Create data object (monolithic combination of all parameters)
		// Omit the blacklisted params (like JSONP callback param, etc.)

		// Allow customizable blacklist for params NOT to include as values.
		req.options.values = req.options.values || {};
		req.options.values.blacklist = req.options.values.blacklist;

		// Validate blacklist to provide a more helpful error msg.
		var blacklist = req.options.values.blacklist;
		if ( blacklist && !_.isArray( blacklist ) ) {
			throw new Error( 'Invalid `req.options.values.blacklist`. Should be an array of strings (parameter names.)' );
		}

		// Get values using the model identity as resource identifier
		var values = req.param( _.kebabCase( model.globalId ) ) || {};

		// Omit built-in runtime config (like query modifiers)
		values = _.omit( values, blacklist || [] );

		// Omit any params w/ undefined values
		values = _.omit( values, function ( p ) {
			if ( _.isUndefined( p ) ) return true;
		} );

		// Omit jsonp callback param (but only if jsonp is enabled)
		var jsonpOpts = req.options.jsonp && !req.isSocket;
		jsonpOpts = _.isObject( jsonpOpts ) ? jsonpOpts : {
			callback: JSONP_CALLBACK_PARAM
		};
		if ( jsonpOpts ) {
			values = _.omit( values, [ jsonpOpts.callback ] );
		}

		return values;
	}
642979
function (req, res, options) {
    if (!options) {
      options = {};
    }
    options.operation = 'SAVE';
    options.res = res;
    if (req.params.model) {
      options.model = req.params.model;
    }
    if (req.body) {
      options.item = req.body;
    }
    if (req.params.data) {
      options.data = req.params.data;
    }
    exports.save.before(req, res, options);
    var userId = req.session['user-id'];
    vulpejs.models.save({
      model: options.model,
      item: options.item,
      data: options.data,
      validate: options.validate || false,
      userId: userId,
      callback: {
        success: function (item) {
          if (!vulpejs.utils.execute(options.callback, {
              item: item,
              postedItem: options.item,
              res: res,
            })) {
            exports.save.after(req, res, item);
            res.json({
              item: item,
              postedItem: options.item,
            });
          }
        },
        error: function (error) {
          exports.response.error(options, error);
        },
        validate: function (validate) {
          exports.response.validate(options, validate);
        },
      },
    });
  }
747815
function find(id, callback) {
        var Model, request;

        Model = this;
        request = {
            action : 'findOne',
            model : Model,
            params : {
                id : id
            }
        };
        this.storage.findOne(request, function findOneCallback(data) {
            if (callback) {
                callback(data);
            }
        });
        return this;
    }
426017
function (req, res, next) {
		var scoreId = req.param('id', null);
		var scoreNumber = req.param('number', null);
		var scoreData = req.param('data', null);
		var scoreValue = req.param('value', null);

		if(	scoreId === null ||
			scoreNumber === null ||
			scoreData === null ||
			scoreValue === null){
			return next('Missing properties');
		}

		// Find the score
    	app.models.Scores.findOne(scoreId).exec(function (err, score){
	    	if(err) return next('Failed to get score: ' + err);

	    	if(!score)
	    		return next('Score not found');

	    	var update = {
	    		scores: score.scores || {}
	    	};

	    	update.scores[scoreNumber] = {
	    		value: parseInt(scoreValue),
	    		data: scoreData,
	    	};

	    	// console.log(update);
	    	// next();
	    	app.models.Scores.update(score.id, update, function (err, model){
	    		if(err) return next(err);
	    		console.log(model);
	    		return res.json(model && model[0]);
	    	});
    	});
	}
445173
function initModelRead (args) {
    var controller = this
    var model = this.model
    // if model does not have id column then cannot use default controller
    if (!model.columnName('id')) {
        return
    }
    // make sure args is object
    args = requireValidOptionalObject(args)
    // make sure read is defined
    args.read = requireValidOptionalObject(args.read)
    // make sure query args are object
    var queryArgs = requireValidOptionalObject(args.read.query)
    // if specific with records not specified then default to model relations
    if (!defined(queryArgs.with)) {
        queryArgs.with = {}
        // load related records
        _.each(model.relations, (relation, relationName) => {
            // add all related models - limit results to 20
            queryArgs.with[relationName] = {
                limit: 20,
            }
        })
    }
    // if with is false do not load any related records
    if (queryArgs.with === false) {
        delete queryArgs.with;
    }
    // get role
    var role = args.defaultRole || 'all'
    // save forms
    var forms = args.read && args.read.forms
    // index inputs
    var input = {
        // get current revision of instance
        current: 'query.current',
        // get record even if deleted
        deleted: 'query.deleted',
        // instance id
        id: 'params.id',
    }
    // links to display at top of page
    var links
    // use links from read view
    if (Array.isArray(args.read.links)) {
        links = _.cloneDeep(args.read.links)
    }
    // use global controller links
    else if (Array.isArray(args.links)) {
        links = _.cloneDeep(args.links)
    }
    // set default links
    else {
        links = []
    }
    // create path if it does not exist
    if (!this.paths['/:id']) {
        this.paths['/:id'] = {}
    }
    // add handler for GET /:id to get model instance
    this.paths['/:id'].get = [
        {
            before: function (args) {
                return beforeRead(controller, args, forms, queryArgs)
            },
            input: input,
            method: function (args) {
                // format response
                return read(controller, args, links)
            },
            methodName: 'read',
            role: role,
            template: 'instance',
        },
    ]
}
943384
function (req, res) {
        var id = req.params.id;
        {modelName}.findOne({_id: id}, function (err, {name}) {
            if (err) {
                return res.status(500).json({
                    message: 'Error when getting {name}',
                    error: err
                });
            }
            if (!{name}) {
                return res.status(404).json({
                    message: 'No such {name}'
                });
            }

            {updateFields}
            {name}.save(function (err, {name}) {
                if (err) {
                    return res.status(500).json({
                        message: 'Error when updating {name}.',
                        error: err
                    });
                }

                return res.json({name});
            });
        });
    }
818539
function(model) {
    if (model.isNew())
      return false
    this.localStorage().removeItem(this.name+"-"+model.id);
    this.records = _.reject(this.records, function(id){
      return id === model.id.toString();
    });
    this.save();
    return model;
  }
1297265
function assertNoEmptyValues(data) {
  _.each(data, function (value) {
    if (!value) {
      throw new Error('Client: page cannot have empty values');
    }
  });

  _.each(references.listDeepObjects(data), assertNoEmptyValues);
}
1100471
function(model, settings, options, cb) {
      var baseQuery, defaultSelect, k, query, v;
      if (settings == null) {
        settings = {};
      }
      if (options == null) {
        options = {};
      }
      if (cb == null) {
        cb = function() {};
      }
      Hoek.assert(model, i18n.assertModuleRequired);
      defaultSelect = settings.defaultSelect || null;
      baseQuery = settings.baseQuery || {};
      if (_.isFunction(options)) {
        cb = options;
        options = {};
      }
      options.where || (options.where = {});
      options.select || (options.select = defaultSelect);
      for (k in baseQuery) {
        v = baseQuery[k];
        options.where[k] = v;
      }
      query = model.findOne(options.where);
      if (options.select && options.select.length > 0) {
        query = query.select(options.select);
      }
      return query.exec(cb);
    }
745858
function(model, options) {
      this._byId[model.cid] = model;
      if (model.id != null) this._byId[model.id] = model;
      if (!model.collection) model.collection = this;
      model.on('all', this._onModelEvent, this);
    }
1363074
function(model, name) {
                if (!model.resource) {
                    return;
                }

                var resource = model.resource.replace(/\/+$/, "");
                if (name === "findAll" || name === "create") {
                    return resource;
                } else {
                    return resource + "/{" + model.id + "}";
                }
            }
371329
function (model, filter, value) {

    if (!_.isString(filter)) {
        return null;
    }

    if (model.data) {
        var list = findKeys(model.data, filter)
            , values = [];

        for (var res in list) {

            if (value === undefined || list[res][filter] === value) {
                values.push(res);
            }
        }
    }
    //return _.isEmpty(values) ? undefined : values;
    //Changed to return empty array instead of 'undefined'. Do not change back, otherwise some functions working with arrays do not work properly.
    return values;
}
67702
function modelQuery(options) {
            return models.Post.findOne(options.data, omit(options, ['data']))
                .then((model) => {
                    if (!model) {
                        return Promise.reject(new common.errors.NotFoundError({
                            message: common.i18n.t('errors.api.posts.postNotFound')
                        }));
                    }

                    return {
                        posts: [urlsForPost(model.id, model.toJSON(options), options)]
                    };
                });
        }
1029395
function(model) {
		var _d = this._d; // quicker lookup
		if (!_d.hasData) {
			// if we've never rendered data yet, queue up a reset collection
			// this probably means we just finished our very first fetch
			// reset needed to clear out loading / no data state..
			return this.resetCollection();
		}
		_d.modelChanges[model.cid] = {t: 'add', m: model};
		this.updateViews();
	}