Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...