首页 > javascript > 在MongoDB中查询嵌套数组

在MongoDB中查询嵌套数组 (Querying a nested array in MongoDB)

问题

这是我posting在MongoDB中的文档:

{
    "_id": {
    "$oid": "5b4e60ab24210138f5746402"
},
    "type": [
    "full",
    "temp"
],
    "applications": [
    {
        "_id": {
            "$oid": "5b52113d1123631744fa9f39"
        },
        "applicationDate": {
            "date": 20,
            "day": 5,
            "hours": 18,
            "minutes": 43,
            "month": 6,
            "seconds": 41,
            "time": 1532105021753,
            "timezoneOffset": -120,
            "year": 2018
        },
        "userId": {
            "$oid": "5b51fb6f9686430cee31a0d9"
        },
        "resume": {
            "fieldname": "resume",
            "originalname": "resume_acc.pdf",
            "encoding": "7bit",
            "mimetype": "application/pdf",
            "destination": "./public/resumes/",
            "filename": "765d650b9014cc3ddadb801d10d495a5",
            "path": "public/resumes/765d650b9014cc3ddadb801d10d495a5",
            "size": 8
        },
        "coverLetter": {
            "fieldname": "docs",
            "originalname": "cover letter.pdf",
            "encoding": "7bit",
            "mimetype": "application/pdf",
            "destination": "./public/resumes/",
            "filename": "e5892869b24f3fc5e72d3e057b4dd61d",
            "path": "public/resumes/e5892869b24f3fc5e72d3e057b4dd61d",
            "size": 5
        }
    }
],
    "creatorId": {
    "$oid": "5b4b95cc16778c325010a55d"
},
    "title": "Developer",
    "salary": "50/h",
    "timeLine": "One year",
    "description": "You'll be building apps",
    "duties": "Building apps",
    "experience": "2 years",
    "province": "ON",
    "visible": true,
    "__v": 0
}

Postings是一个数组posting,看起来像上面的文档。applications是一个在每一个中的数组posting。我想搜索所有postings.applications以查看用户应用的所有帖子。现在我试着这样做:

var Posting = require('../models/posting');
var postings = await Posting
    .find({'visible': true});
console.log('posts', postings);
var applications = await Posting
    .find({'visible': true})
    .where(postings
        .map(posting => posting.applications
            .map(application => application.userId.equals(req.user._id)))
    );

但显然这失败了。

我也尝试过这个:

var postings = await Posting
    .find({'visible': true, 'applications[$].userId': req.user._id});

要么

var postings = await Posting
    .find({'visible': true, 'applications.$.userId': req.user._id});

但没有运气。它们都返回一个空数组。

发布模式:

var mongoose = require('mongoose');

jobPostingSchema = mongoose.Schema({
    "creatorId": mongoose.Schema.Types.ObjectId, //ObjectID('aaaa'), // ID of the User or Account
    "eventId": {'type': mongoose.Schema.Types.ObjectId, 'default': undefined},
    "title": String,
    "type": [], //"Full", // What this means? I did not understand.
    "salary": String,
    "timeLine": String, // What this means? I did not understand.
    "description": String,
    "duties": String,
    "experience": String,
    "province": String, // Employer will post job postings based on the province and region
    // Applications means, how many people applied for this job post?
    "applications": [
        // {
        //     ObjectID: cccc,
        //     userId: dddd,
        //     Resume: {},
        //     coverLetter: String,
        // },
    ],
    "visible": Boolean,
});

module.exports = mongoose.model('posting', jobPostingSchema);

所以,我怎么能得到所有applications地方userId等于req.user._id

解决方法

也许这可以作为一个解决方案(从SO的连接由@DSCH共享采购这里):

Posting.find({
    'applications': {
        $elemMatch: { userId: req.user._id }
    },
    'visible:': true
});

如果您想了解其工作原理,请参阅此处的链接

问题

This is my posting document in MongoDB:

{
    "_id": {
    "$oid": "5b4e60ab24210138f5746402"
},
    "type": [
    "full",
    "temp"
],
    "applications": [
    {
        "_id": {
            "$oid": "5b52113d1123631744fa9f39"
        },
        "applicationDate": {
            "date": 20,
            "day": 5,
            "hours": 18,
            "minutes": 43,
            "month": 6,
            "seconds": 41,
            "time": 1532105021753,
            "timezoneOffset": -120,
            "year": 2018
        },
        "userId": {
            "$oid": "5b51fb6f9686430cee31a0d9"
        },
        "resume": {
            "fieldname": "resume",
            "originalname": "resume_acc.pdf",
            "encoding": "7bit",
            "mimetype": "application/pdf",
            "destination": "./public/resumes/",
            "filename": "765d650b9014cc3ddadb801d10d495a5",
            "path": "public/resumes/765d650b9014cc3ddadb801d10d495a5",
            "size": 8
        },
        "coverLetter": {
            "fieldname": "docs",
            "originalname": "cover letter.pdf",
            "encoding": "7bit",
            "mimetype": "application/pdf",
            "destination": "./public/resumes/",
            "filename": "e5892869b24f3fc5e72d3e057b4dd61d",
            "path": "public/resumes/e5892869b24f3fc5e72d3e057b4dd61d",
            "size": 5
        }
    }
],
    "creatorId": {
    "$oid": "5b4b95cc16778c325010a55d"
},
    "title": "Developer",
    "salary": "50/h",
    "timeLine": "One year",
    "description": "You'll be building apps",
    "duties": "Building apps",
    "experience": "2 years",
    "province": "ON",
    "visible": true,
    "__v": 0
}

Postings is an array of posting, which look like the above document. applications is an array which is in every posting. I want to search all postings.applications to see get all postings the user applied to. For now I tried to do it like this:

var Posting = require('../models/posting');
var postings = await Posting
    .find({'visible': true});
console.log('posts', postings);
var applications = await Posting
    .find({'visible': true})
    .where(postings
        .map(posting => posting.applications
            .map(application => application.userId.equals(req.user._id)))
    );

But obviously this failed.

I tried this as well:

var postings = await Posting
    .find({'visible': true, 'applications[$].userId': req.user._id});

or

var postings = await Posting
    .find({'visible': true, 'applications.$.userId': req.user._id});

But no luck. They both return an empty array.

Posting model:

var mongoose = require('mongoose');

jobPostingSchema = mongoose.Schema({
    "creatorId": mongoose.Schema.Types.ObjectId, //ObjectID('aaaa'), // ID of the User or Account
    "eventId": {'type': mongoose.Schema.Types.ObjectId, 'default': undefined},
    "title": String,
    "type": [], //"Full", // What this means? I did not understand.
    "salary": String,
    "timeLine": String, // What this means? I did not understand.
    "description": String,
    "duties": String,
    "experience": String,
    "province": String, // Employer will post job postings based on the province and region
    // Applications means, how many people applied for this job post?
    "applications": [
        // {
        //     ObjectID: cccc,
        //     userId: dddd,
        //     Resume: {},
        //     coverLetter: String,
        // },
    ],
    "visible": Boolean,
});

module.exports = mongoose.model('posting', jobPostingSchema);

So how can I get all applications where userId equals req.user._id?

解决方法

Maybe this works as a solution ( sourcing from the SO link shared by @DSCH here ):

Posting.find({
    'applications': {
        $elemMatch: { userId: req.user._id }
    },
    'visible:': true
});

If you wish to seek clarification on how it works, you may refer to the link here

相似信息