I want to query an array of a subdocument using the "token" property in clientSchema. But I cannot fill in an array of subdocuments. It always returns an empty value.
This is what I tried
var performAuthAsync = promise.promisify(performAuth);
var response = {};
performAuthAsync(req).then(function (client) {
sendStatus(res, 200, { "success": "true", "value": client });
}).catch(ApiError, function (e) {
response.error = "true";
response.message = e.message;
if (e.message == "Invalid Authorization" || e.message == "Unauthorized access") {
console.log(e.message);
sendStatus(res, 401, response, req.query.type);
}
else {
sendStatus(res, 500, response, req.query.type);
}
});
PerformAuth Method
function performAuth(req, callback) {
try {
var authHeader = req.headers.authorization;
console.log(authHeader);
if (!authHeader || !authHeader.startsWith("Basic ")) {
console.log("inside fail authheader");
return callback(new ApiError("Invalid Authorization"));
}
authHeader = authHeader.replace("Basic ", "");
authHeader = Buffer.from(authHeader, 'base64').toString('ascii');
console.log(authHeader);
clientApp.findOne({}).populate({
path: 'appClients',
model: 'TClient'
}).exec(function (error, apps) {
console.log("populated apps check " + apps);
});
clientApp.findOne({}).populate('appClients').findOne({
'appClients.token': authHeader
}).exec(function (error, client) {
if (error) {
console.log("inside dberror");
console.error(error);
return callback(error, null);
}
if (!client) {
return callback(new ApiError("Unauthorized access"), null);
}
return callback(client);
});
}
catch (exception) {
console.log("inside exception");
console.error(exception);
return callback(exception, null);
}
}
Client and client schemes: (they are in different files)
var appSchema = new Schema({
appId: {
type: String,
required: true,
unique: true
},
appSecret: {
type: String,
required: true,
unique: true
},
appClients: [{ type: Schema.Types.ObjectId, ref: 'TClient' }],
createdAt: Date,
modifiedAt: Date
});
var clientApp = mongoose.model('ClientApp', appSchema);
var clientSchema = new Schema({
clientId: {
type: String,
required: true,
unique: true
},
info: {
type: String,
required: true,
},
token: {
type: String,
required: true,
unique: true
},
createdAt: Date,
modifiedAt: Date
});
var tclient = mongoose.model('TClient', clientSchema);
What am I doing wrong? Any help is appreciated.