如何通过使用Mongoose查询子文档来查找父文档?

时间:2015-12-18 00:26:07

标签: node.js mongodb mongoose mongoose-schema

在下面的示例中,如何找到特定成员ID具有Account(子文档)的Membership(父)文档?我尝试过使用$elemMatch和直接查询对象。

注意: 两个模式都有一个已删除的标志字段(dd)。如果设置了此字段,则记录已被删除,不应返回:

var mongoose    = require('mongoose')

var membershipSchema = new mongoose.Schema({

    m : { type: mongoose.Schema.ObjectId, ref: 'member' },      // Member
    b : { type: Date, required: true },                         // Begin Date
    e : { type: Date },                                         // End Date

    dd  : { type: Date },                                       // Deleted Date
    dm  : { type: mongoose.Schema.ObjectId, ref: 'member' }     // Deleted By Member
});

var accountSchema = new mongoose.Schema({

    n   : { type: String, trim: true },                         // Display Name

    m   : [ membershipSchema ],                                 // Membership List

    dd  : { type: Date },                                       // Deleted Date
    dm  : { type: mongoose.Schema.ObjectId, ref: 'member' }     // Deleted By Member
});

var accountModel = mongoose.model('account', accountSchema);

module.exports = accountModel;

我想返回所有Account文档,无论是否包含Membership子文档。但是,在执行查询时,我对Account一无所知。

这就是我的尝试:

var query = {
    m : {
        $elemMatch: {
            m  : req.appData.member.id,
            dd : { $exists: false }
        }
    },
    dd : { $exists: false }
};

Account.find(query, function (err, accounts) {
    // Do something
});

1 个答案:

答案 0 :(得分:1)

我已多次测试过,上面的语法是正确的。如图所示使用void Java_com_App_SimpleFunction(JNIEnv * env, jobject this, jint size) { (*env)->GetJavaVM(env, &jvm); int address=0; for(address=0;address<(int)(size);address++) { value=buffer_read_byte(address)&0xFF; /* some data manipulation on ""value"" */ buffer_byte_write(address,value); } return; } uint8_t buffer_read_byte(jint pos) { JNIEnv * env; jint rs=(*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4); JavaVMAttachArgs args; args.version = JNI_VERSION_1_6; // choose your JNI version args.name = NULL; // you might want to give the java thread a name args.group = NULL; // you might want to assign the java thread to a ThreadGroup jint rs=(*jvm)->AttachCurrentThread(jvm, (void**)&env, &args); //... return value; } uint8_t buffer_byte_write(jint pos, jint data) { JNIEnv * env; jint rs=(*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_4); JavaVMAttachArgs args; args.version = JNI_VERSION_1_6; // choose your JNI version args.name = NULL; // you might want to give the java thread a name args.group = NULL; // you might want to assign the java thread to a ThreadGroup jint rs=(*jvm)->AttachCurrentThread(jvm, (void**)&env, &args); //... return; } 对象将导致返回所有顶级query对象,其中成员的ID存在于子文档中。并且,通过检查Account字段(您的删除标志)的存在(或缺少),只有未标记为&#34;删除的对象&#34;将被退回。

以防您需要调整原始问题。这是我们正在讨论的正确语法:

dd