Rishi Kumar
Rishi Kumar

Reputation: 11

Geting empty array when find with some criteria in mongoose

Schema :

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var Config = require('../Config');

var serviceAvailability = new Schema({
    agentId: {type: Schema.ObjectId, ref: 'agentProfile', required: true},
    availabilityDate: {type: Date, required: true},
    availabilityTime: {type: Array, required: true} 
});

serviceAvailability.index({agentId:1 , availabilityDate:1},{unique:true});

module.exports = mongoose.model('serviceAvailability', serviceAvailability);

Controller :

Models.serviceAvailability.find({'agentId':'abcd'}, function (err, service) {
    console.log(service);
    if(service) {
        callback(err , service);
    }
    else {
        callback(err);
    }
});

I am trying to get all data with some criteria like if agentId is equal to some value but whenever i am using any criteria to find data i am getting empty array while if i remove the criteria and find all data then i am getting data, why is this ?

Upvotes: 1

Views: 60

Answers (1)

throrin19
throrin19

Reputation: 18207

I think, you try to find a mongoDB document with a request on ObjectId Field, but, in your example, you don't use a correct ObjectId String Value.

ObjectId is a 12-byte BSON type, constructed using:

So, this is a correct way to request your serviceAbility with a correct ObjectId :

Models.serviceAvailability.find({
    'agentId':'507f1f77bcf86cd799439011'
}, function (err, service) {
    if (err) {
        callback(err);
        return;
    }
    callback(null, service);
});

In this case, you should have an agentProfile with the _id equals to 507f1f77bcf86cd799439011

Upvotes: 1

Related Questions