简体   繁体   中英

How to find object in array of objects mongoose

I have this schema (groupschema)

const mongoose = require('mongoose')

const GroupSchema = new mongoose.Schema({
CreatedBy:String,
Name:String,
Link:String,
Password:String,
Periods:Number,
Members:Array,

})

module.exports = mongoose.model('groups', GroupSchema, 'groups')

And Members is an array of objects. This is how members is stored.

   Members[ {
    Email:req.user.email,
    DisplayName:displayname,
    GoogleId:req.user.googleId,
    Image:req.user.image,
    }]

I want to find the each user's object with their googleId. How do I find their objects with just their googled looking through every single group document?

I've tried this, but it keeps returning an empty array.

 const datafound = await groupschema.find({ "Members": { googleId: req.user.googleId } });

Thank you

Fixed:

I did

 const datafound = await groupschema.findOne({'Members': {$elemMatch: {googleId: req.body.googleId}}})

To match it to an object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM