简体   繁体   中英

Mongoose query returning arrays as undefined

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.

Try this:

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

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

hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM