I'm working on an mongo database with mongoose in Node.js.
I have a collection like this :
{
cinema: 'xxx',
account: 'yyy',
media: {
data: [{
id: 1,
name: 'zzz'
}, {
id: 2,
name: 'zzz'
},
...
]
}
}
Schema:
const dataCacheSchema = new mongoose.Schema(
{
cinemaName: String,
account: String
},
{ timestamps: true, strict: false }
);
The list of data can be long. I would like to retrieve a single media from a findOne query :
{
id: 1,
name: 'zzz'
}
I've tried like this :
const doc: mongoose.Document[] | null = await DataCache.findOne(
{
cinemaName: ci.cinema,
account: ci.account,
'media.data': { $exists: true, $elemMatch: { id: mediaId } }
},
{ media: { data: { $elemMatch: { id: mediaId } } } }
).exec();
But it crashes with the error message :
MongoError: Cannot use $elemMatch projection on a nested field.
media.datais an array of objects? You might have to put the these objects in a separate collection.