Reputation: 27
varyantalt Model:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const varyantaltSchema = new Schema({
_id: {
type: Schema.ObjectId
},
varyantid: {
type: String
},
altvaryantname: {
type: String
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("varyantalt", varyantaltSchema, "varyantalt");
varyant model:
const varyantSchema = new Schema({
_id: {
type: Schema.ObjectId
},
stokid: {
type: Schema.ObjectId
},
varyantname: {
type: String
},
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("varyant", varyantSchema, "varyant");
varyant collection:
{
"_id": ObjectId("5e32286c34fb7322bdd566ed"),
"stokid": ObjectId("5e28b4a2a1d9692b29a65b24"),
"varyantname": "RENK"
}
altvaryant collection:
{
"_id": ObjectId("5e3228df34fb7322bdd566f5"),
"varyantid": "5e32286c34fb7322bdd566ed",
"altvaryantname": "KIRMIZI",
"vars": [
{
"_id": ObjectId("5e35b1e410fce83f3370cd0a"),
"images": {
"imageurl": "http://",
"_id": ObjectId("5e35b1e410fce83f3370cd0b"),
"filename": "5320_7d93",
"path": "https://res",
"publicid": "panel"
}
}
]
},
{
"_id": ObjectId("5e3359e6fa4c5e4bd9112fb6"),
"varyantid": "5e32286c34fb7322bdd566ed",
"altvaryantname": "SARI",
"vars": [
{
"_id": ObjectId("5e35b1f610fce83f3370cd0d"),
"images": {
"imageurl": "http://",
"_id": ObjectId("5e35b1f610fce83f3370cd0e"),
"filename": "veli-fidan-1LT-2-450x450",
"path": "https://",
"publicid": "panel"
}
}
]
},
{
"_id": ObjectId("5e335b64fa4c5e4bd9112fc9"),
"varyantid": "5e32286c34fb7322bdd566ed",
"altvaryantname": "YEŞİL",
"vars": [
{
"_id": ObjectId("5e35b20010fce83f3370cd10"),
"images": {
"imageurl": "http://",
"_id": ObjectId("5e35b20010fce83f3370cd11"),
"filename": "maxresdefault-29-450x450",
"path": "https://",
"publicid": ""
}
}
]
}
Query:
varyant
.aggregate([
{
$match: {
stokid: mongoose.Types.ObjectId("5e28b4a2a1d9692b29a65b24")
}
},
{
$lookup: {
from: "varyantalt",
localField: "_id",
foreignField: "varyantid",
as: "vars"
}
},
{ $unwind: "$vars" }
])
.exec((err, locations) => {
if (err) throw err;
console.log("res::", locations);
});
I am trying to get results with $aggregate
and $lookup
query with mongoose
Why is my query returning empty? I couldn't find the problem.
Under $lookup
operator from: 'varyantalt'
I do not understand exactly whether it takes a blank value. Thanks in advance for your help.
Upvotes: 0
Views: 1072
Reputation: 17858
In your varyantaltSchema
schema, varyantid
is defined as String, but it must be Schema.ObjectId
.
They must be same because $lookup performs an equality match on the foreignField to the localField from the input documents
If you save your varyandid as Object id aggregate will work.
Upvotes: 1