1

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 ?

3
  • Have you checked if Models.agentProfile.findById('abcd') yields a result? Commented Sep 1, 2015 at 6:47
  • 2
    Well "abcd" is not an ObjectId. You need to put in a valid ObjectId value or at least string that equals the hex value returned. Or you seem to be trying to match a "field" within the "agentProfile" objects, and the latter is just not possible. Not without populating and manually filtering. Commented Sep 1, 2015 at 6:47
  • abcd is just to tell you as a example, in real i am sending proper ObjectId, and yes i tried all same query in mongo terminal and then working fine from mongo terminal @robertklep Commented Sep 1, 2015 at 9:47

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I assumed that abcd in the question was just a placeholder :-)
abcd is just to tell you as a example, in real i am sending proper ObjectId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.