I'm trying to set a projection in order to retrieve less data from a query but the problem comes when I try to put inside the projection a field that is an array
This is my piece schema
module.exports = {
name: "attendee",
extend: "apostrophe-pieces",
alias: "attendees",
label: "Attendee",
pluralLabel: "Attendees",
addFields: [
{
name: "_congress",
label: "Congress this attendee has sign up for",
type: "joinByOne",
withType: "congress",
filters: {
projection: {
_id: 1,
title: 1
}
}
},
{
name: "registrationDate",
label: "Registration Date",
type: "date"
},
{
name: "registrationTime",
label: "Registration Time",
def: null,
type: "time"
},
{
name: "fields",
label: "Fields",
type: "array",
titleField: "Array Label",
schema: [
{
name: "name",
type: "string",
label: "String"
},
{
name: "value",
type: "string",
label: "Value"
}
]
}
],
An my query is like this:
return self.find(req, { congressId }).projection({ registrationDate: 1, registrationTime: 1, fields: 1 }).toArray();
When I put fields: 1
I got this exception
Otherwise returns the array as expected:
I also tried this query inside mongo shell and it worked:
> db.aposDocs.find({_id: "ck35z61p400047e9e5ktt6wu4"}).projection( {fields: 1})
{ "_id" : "ck35z61p400047e9e5ktt6wu4", "fields" : [ { "id" : "attende1Field1", "name" : "name", "value" : "Name1" }, { "id" : "attendee1Field1", "name" : "lastName", "value" : "Last Name1" }, { "id" : "attendee1Field1", "name" : "treatment", "value" : "Treatment1" }, { "id" : "attendee1Field1", "name" : "email", "value" : "email1@email.com" } ] }
Maybe I'm missing something? Thanks in advance
This appears to be caused by a MongoDB bug, at least in the 2.x version of the MongoDB nodejs driver. It is specifically the field name fields
that does not work and generates the error you saw:
Failed to parse: projection: 1. 'projection' field must be of BSON type object.
I renamed it to fields2
and everything worked as expected. So your resolution is just to change the name of the array field. It would be interesting to see if this issue still occurs with the apostrophe-mongo-3-driver
module configured.