skip to Main Content

I have two defined two schemas with are filled with data.

// Schema 1

const geoSchema = new Schema({
  ip: String,
  lat: String,
  lon: String,
});

const GeoModel = mongoose.model("geo", geoSchema);

// Schema 2

const ipAddressSchema = new Schema({
  ip: String,
  comment: String,
  mbps: Number,
  pps: Number,
});

const IpAddressModel = mongoose.model("ip-address", ipAddressSchema);

I try to join these two schemas using lookup function through the same filed name, ip specifically.

 const result = await IpAddressModel.aggregate()
    .lookup({
      from: "geo",
      localField: "ip",
      foreignField: "ip",
      as: "geo",
    })
    .exec();

In results i get ip addresses, but the geo field is empty.

{
    "_id": "63fdd490533255bcdbe14683",
    "ip": "172.17.32.19",
    "comment": "",
    "mbps": 1918,
    "pps": 28844,
    "__v": 0,
    "geo": []
}

2

Answers


  1. Try this:

     db.ipAddressSchema.aggregate([
          {
            $lookup: {
              from: "geoSchema",
              localField: "ip",
              foreignField: "ip",
              as: "geo"
            }
          }
        ])
    

    Playground.

    Login or Signup to reply.
  2.     const geoSchema = new mongoose.Schema({
            ip: String,
            lat: String,
            lon: String,
        });
    
        const ipAddressSchema = new mongoose.Schema({
            ip: String,
            comment: String,
            mbps: Number,
            pps: Number,
        });
    
    
        const GeoModel = mongoose.model('geoSchema', geoSchema);
        const IpAddressModel = mongoose.model('ipAddressSchema', ipAddressSchema);
    
    
       IpAddressModel.aggregate([
          {
            $lookup: {
              from: "geoSchema",
              localField: "ip",
              foreignField: "ip",
              as: "geo"
            }
          }
        ]).exec((err, result) => {
          if (err) {
            console.log(err);
          } else {
            console.log(result);
          }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search