Mongoose query returning arrays as undefined

时间:2016-12-02 05:24:54

标签: node.js mongodb mongoose

I currently have a mongoose model that I am saving multiple IDs as an array.

var map = new Schema ({
    "AdminID" : [{type: mongoose.Schema.Types.ObjectId, required: false }],
    "AdminKeys" : [{type: mongoose.Schema.Types.ObjectId, required: false }]
});

When I make a query through the mongo shell, I can see that there are some values in the AdminKeys array.

"_id" : ObjectId("584101b5b2483a57256bdf16"),
"AdminID" : [ ],
"AdminKeys" : [
        ObjectId("583b5f0b9a64391584e4b4ad")
]

However, in my controller, when I try and do

Map.findOne({_id: ObjectId('584101b5b2483a57256bdf16')}, 
{_id : 0, AdminID: 1, AdminKeys: 1 } (err, map) => {

      if (err) {
        console.log(err);
        return;
      }
      console.log(map);
}

I am left with undefined array fields and cannot access any of the values within my AdminKeys array.

_doc: 
     { AdminID: undefined,
       AdminKey: undefined },
'$__original_save': [Function],

If someone would be so kind to help me understand what is going on and a work around, It would be much appreciated.

1 个答案:

答案 0 :(得分:2)

试试这个:

Map.findOne({_id: ObjectId('584101b5b2483a57256bdf16')}, 'AdminID AdminKeys',function(err, map) {

  if (err) {
    console.log(err);
    return;
  }
  console.log(map);
});

希望这有助于:)