wend try with this query, return the lookup is empty
db.getCollection(\'tests\').aggregate([
{$match: {typet:\'Req\'}},
{$project: {incharge:1}},
First, assert that the type of the incharge
field is mongoose.Schema.Types.ObjectId
. If you still get an empty array back it might be because you are using the schema name you declared in NodeJS instead of the collection name used by MongoDB.
Example from a UserSchema
file:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const UserSchema = new Schema({
name: {
type: String,
required: true
},
incharge: {
type: Schema.Types.ObjectId,
required: true
},
})
const User = mongoose.model('User', UserSchema)
module.exports = User
The model above is named User
by mongoose but the corresponding collection in mongoDB is named users
. The resulting $lookup
is written as:
$lookup:{
from: "users", // name of mongoDB collection, NOT mongoose model
localField: "incharge", // referenced users _id in the tests collection
foreignField: "_id", // _id from users
as: "user" // output array in returned object
}
https://mongoosejs.com/docs/models.html
https://mongoosejs.com/docs/schematypes.html