Suppose I have a collection in my mongoDB: db.co
and only have one document:
{ \"_id\" : ObjectId(\"50d083e32cdcf7ce065b616c\"),
\"age\" : 22
.find() works asynchronous, meaning that its callback runs when your function already has.
see variable scope in asynchronous function
//try passing a callback function to your search function, like:
function findSomeoneInCo (name, callback) {
//happens now - here you could still return something
Co.find({"name": name}, function (err, doc) {
//happens later - too late to return stuff, function has ran already
if (err) {
callback(err);
return;
}
callback(doc);
})
}
//call your function passing a callback function
findSomeoneInCo("lee", function(doc){
console.log('do something with your results: ' + doc);
});
I notice your callback to find() has the following parameters : err, doc
find() always returns an array so you really want this to be : err, docs
OR use findOne()
The async stuff shouldn't be a problem in the code you've posted, the nested callbacks will still be executed. Are you sure your connection is OK. I would run an open query :
Co.find({}, function(err, docs){
console.log(docs);
}
Just to check the collection has something in it
Mongoose pluralizes the lower-cased model name when determining the collection name to use. So with a model name of 'Co'
it's going to be looking in the cos
collection by default.
To override the default and align with your existing co
collection:
var Co = mongoose.model('Co', coSchema, 'co');
Mongoose pluralizes your model name during any CURD operation, Use this & check :
var Co = mongoose.model('Co', coSchema, 'co'); //Even the case matters
or
var coSchema = new Schema({
age: Number,
friends: Array,
location: String,
name: String,
skill: Array
}, {collection:'co'});
var Co = mongoose.model('Co',coSchema);