如果我有以下物品:
var person = {
fname: "Joe",
lname: "Shmoe",
misc: {
age: "25",
gender: "M",
hair: "blonde"
}
}
我需要使用mongoose检查这个确切的人是否在数据库中。我想做的是
Person.findOne(person, function(err, result) {
if (!result) {
...
}
}
有没有办法使用mongoose检查整个对象是否作为文档存在,而无需手动输入所有字段?
编辑:这是我目前正在做的事情:
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) {
...
}
});
答案 0 :(得分:0)
不确定你在这里问什么,好像你只是传入你定义为查询的第一个参数的person
变量,那么你将获得完全匹配的结果。附带条件是“misc”中的键必须与实际文档中的顺序相同,否则如果该顺序并非总是相同,则需要使用“点符号”:
{
"fname": "Joe",
"lname": "Schmoe",
"misc.age": "25",
"misc.gender": "M",
"misc.hair": "blonde"
}
并且您不难从初始对象转换:
var obj = {};
for ( var k in person ) {
if ( "k" == "misc" ) {
for ( var b in person[k] ) {
obj["misc." + b] person[k][b];
}
} else {
obj[k] = person[k];
}
}
然后您可以使用obj
作为查询参数,因为它具有“点表示法”形式:
一般情况下,它应该没问题,除非你已经转换为具有不同_id
值的Mongoose文档。一些代码来证明这一点:
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 data = {
fname: "Joe",
lname: "Shmoe",
misc: {
age: "25",
gender: "M",
hair: "blonde"
}
};
var person = new Person( data );
var other = new Person( data );
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();
});
},
]);