Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'
        }
      }   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...