一个成员是一个或多个组的一部分。一个小组可以有一个或多个成员。
鉴于有一名成员及其所在的团体,我如何才能获得其中每个团体中的其他成员?
var MemberSchema = new Schema(
{
name: {
first: { type: String },
last: { type: String },
},
groups: [ { type: String } ],
otherMembersInGroups: [ {
id: { type: Schema.ObjectId, ref: 'Member' } ,
name: {
first: { type: String },
last: { type: String },
}
} ],
});
var query = MemberModel.findOne( { _id: objId } );
query.exec( function( err, member )
{
// TODO: get all the members in all the groups that this member is in
var otherMembersInGroups = magicHere();
member.otherMembersInGroups = otherMembersInGroup;
return res.send( 200, member );
}
我的出发点是
var query = MemberModel.find( { groups: "groupNamesHere" } )
但我真的不明白如何将其与上述结合起来。
另外:如何正确地将此字段添加到猫鼬模型?我试过,但有很多重复(见上文)。但似乎没有将它添加到模型中,它实际上并没有被添加到成员对象中?
答案 0 :(得分:1)
对于我来说,我对“Schema”的定义并不那么正式,并且处理它有点不同。考虑定义如下的模式:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var memberSchema = new Schema({
name: {
first: { type: String },
last: { type: String }
},
groups: [ { type: String } ]
});
var Member = mongoose.model( 'Member', memberSchema );
使用这样的数据:
{
"_id" : ObjectId("53708c9865a6272f6e26c9bf"),
"groups" : [ "tennis" ],
"name" : { "first" : "Ted", "last" : "Logan" },
"__v" : 0
}
{
"_id" : ObjectId("53708cb33905d7846ee2a218"),
"groups" : [ "tennis", "hockey" ],
"name" : { "first" : "Bill", "last" : "Preston" },
"__v" : 0
}
{
"_id" : ObjectId("53708cd200155f916e9248f6"),
"groups" : [ "perl", "hockey" ],
"name" : { "first" : "Fozzie", "last" : "Bear" },
"__v" : 0
}
{
"_id" : ObjectId("53708ce7c95556e66ee4967f"),
"groups" : [ "perl", "hockey" ],
"name" : { "first" : "Serena", "last" : "Williams" },
"__v" : 0
}
其余操作如下:
Member.findOne({ _id: "53708cb33905d7846ee2a218" },function(err,member) {
Member.find({
"groups": { "$in": member.groups },
"_id": { "$nin": [ member._id ] }
},function(err, others) {
var data = {
name: member.name,
groups: member.groups,
otherMembers: []
};
others.forEach(function(other) {
var doc = {};
doc.name = other.name;
doc._id = other._id;
data.otherMembers.push( doc );
});
console.log( data );
});
});
当然用您的实际API函数替换console.log()
部分。但通常原始对象比“模式”具有更少的操作规则,因此更容易控制结果。
同时确保您按照该顺序指定了索引,其中“groups”是第一个要优化此元素的元素。