简体   繁体   中英

$lookup returning empty array

I have a students collection and a classes collection student._id(ObjectId) needs to match in a lookup of the files collection on classes.owner(String). I am getting empty array for files. What am I doing wrong?

var express = require('express');
var router = express.Router();
var Account = require('../models/account');
var Connections = require('../models/connections');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;


//get all advocates for student.
router.route('/:student_id?')

  .get(function (req, res) {

    Account.aggregate(
      { "$match": { "_id": mongoose.Types.ObjectId(req.params.student_id) } },
      {$lookup:
        {
          from: 'classes',
          localField: 'owner',//**String**
          foreignField: '_id', //**ObjectId**
          as: 'classes'
        }
      }       
    ).exec(function (err, doc) {
        console.log(doc[0]);
        if (err) {
          res.send(err);
        } else {
          res.send(doc[0]).end();
        }
      })
  });


module.exports = router;

check you from clause, is it your collection name? I used schema name instead of the collection name which results in empty result.

{$lookup:
        {
          from: 'classes',  //check this
          localField: 'owner',//**String**
          foreignField: '_id', //**ObjectId**
          as: 'classes'
        }
      }   

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