mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

find() issue

Open segsalerty2013 opened this issue 10 years ago • 3 comments

example schemas:

var aSchema = mongoose.Schema({
    b_id:{type:Schema.ObjectId, ref:'B'},
    happen_time:{type:Date, default:Date.now},
    channel:{type:String, required:true},
    cost_amount:{type:Number, min:0, required:true},
});
var bSchema = mongoose.Schema({
 name: String
 address: String
);

So, i like to find all the B using his ref id in A I have tried:

A.find({"b_id": someString}, function(err, all){});
A.find({"b_id": mongoose.Schema.ObjectId(someString)}, function(err, all){});
A.find({"b_id": mongoose.Types.ObjectId(someString)}, function(err, all){});

All giving me empty result.

So, how do i select from A all document with same b_id

segsalerty2013 avatar Jul 13 '16 12:07 segsalerty2013

The third is the correct way to go, if someString is something like this: 577ce4cc38aba07c24fb04ce. Also, make sure that in your code you have (javascript code):

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

I can't think of anything else right now, let me know if you find a solution.

enrichz avatar Jul 13 '16 12:07 enrichz

Thanks @enrichz , Appreciate

Later figured the issue and A.find({"b_id": someString}, function(err, all){}); Worked

segsalerty2013 avatar Jul 13 '16 13:07 segsalerty2013

First way is the way to go, although third way also works, mongoose should automatically coerce the string into an objectid for you

vkarpov15 avatar Jul 15 '16 19:07 vkarpov15