Tuesday, 15 June 2010

node.js - Checking if entire object exists in db with mongoose -



node.js - Checking if entire object exists in db with mongoose -

if have next object:

var person = { fname: "joe", lname: "shmoe", misc: { age: "25", gender: "m", hair: "blonde" } }

and need check whether exact person in database using mongoose. i'd along lines of

person.findone(person, function(err, result) { if (!result) { ... } }

is there way check if entire object exists document in database using mongoose without manually entering in of fields?

edit: here i'm doing:

person.findone({ fname: person.fname }) .where('lname').equals(person.lname) .where('misc.age').equals(person.misc.age) .where('misc.gender').equals(person.misc.gender) .where('misc.hair').equals(person.misc.hair) .exec(function(err, result) { if (!result) { ... } });

not sure asking here if pass in person variable have defined first argument query result match. proviso there keys in "misc" must in same order within actual document or otherwise required utilize "dot notation" if order not same:

{ "fname": "joe", "lname": "schmoe", "misc.age": "25", "misc.gender": "m", "misc.hair": "blonde" }

and not hard convert initial object:

var obj = {}; ( var k in person ) { if ( "k" == "misc" ) { ( var b in person[k] ) { obj["misc." + b] person[k][b]; } } else { obj[k] = person[k]; } }

then can utilize obj query argument has "dot notation" form:

generally though case should okay, unless have cast mongoose document differing _id value. code demonstrate this:

var mongoose = require('mongoose'), async = require('async'), schema = mongoose.schema; mongoose.connect('mongodb://localhost'); var personschema = new schema({ fname: string, lname: string, misc: { age: string, gender: string, hair: string } }); var person = mongoose.model( "person", personschema, "person" ); var info = { fname: "joe", lname: "shmoe", misc: { age: "25", gender: "m", hair: "blonde" } }; var person = new person( info ); var other = new person( info ); console.log( person ); async.series([ function(callback) { person.save(function(err,person) { callback(); }); }, function(callback) { console.log( "this works" ); person.findone( data, function(err,person) { console.log( "person: " + person ); callback(); }); }, function(callback) { console.log( "this doesn't" ); person.findone( other, function(err,person) { console.log( "person: " + person ); callback(); }); }, function(callback) { console.log( "this does" ); var obj = other.toobject(); delete obj._id; person.findone( obj, function(err,person) { console.log( "person: " + person ); callback(); }); }, ]);

node.js mongodb mongoose

No comments:

Post a Comment