Meteor - How To Extract Key Name From Collection? -
i have following in initialize file values loaded in database on startup:
meteor.startup(function() { if(typeof person.findone() === 'undefined') { person.insert({ name: "", gender: ["male", "female", "prefer not say"], age: 0 }); } });
and in server/abc.js have:
meteor.methods({ checkperson: function (input) { (var key in person) { if (input === key) { ... } } } });
this meteor method checkperson called in client side string value being passed argument(input).
i want check 'input' string value against name of key in person collection.
person has key called 'gender'. instance, if 'input' holds string value 'gender' if statement should true in case comes false , hence code inside if statement never executed.
any help/guidance appreciated.
update
i searched on mongodb documentation , found here: http://docs.mongodb.org/manual/reference/operator/query/exists/ , using thread: (using $exists in mongo dynamic key names , native driver node) this:
var checkthis = {}; checkthis[input] = { $exists : true }; var p = person.findone(checkthis);
so if finds 1 'p' holds record or else undefined. still above code not work.
if put directly:
var p = person.find({gender: {$exists: true} });
then works.
so need assistance in getting code work variable 'input'.
mongo schemaless database - can insert document structure collection , data store won't complain. therefore person
won't able indicate fields conform pattern.
the common way people deal problem use package provides schema layer on top of mongo. meteor, popular choice simpleschema, , related package autoform. simpleschema allows define fields should allowed collection, , autoform gives set of helpers enforce them in ui.
if, instead, prefer not use package following:
person.js
var required_fields = { name: string, gender: ['male', 'female', 'prefer not say'], age: number }; person = new meteor.collection('person'); person.isvalid = function(person) { try { check(person, required_fields); return true; } catch (_error) { return false; } }; meteor.methods({ 'person.insert': function(person) { check(person, required_fields); return person.insert(person); } });
my-template.js
template.mytemplate.events({ submit: function() { var person = { name: $('#name').val(), gender: $('#gender').val(), age: parseint($('#age').val(), 10) }; if (person.isvalid(person)) meteor.call('person.insert', person); else alert('invalid person'); } });
here using meteor's check package basic field validation. adding isvalid
helper person
collection, can validate schema without need method call. best of can reuse same check when inserting new document.