NodeJs/MongoDB -查找函数未按预期返回结果

v8wbuo2f  于 2023-03-07  发布在  Go
关注(0)|答案(2)|浏览(132)

我定义了两个模式,其中填充了数据。
//架构1

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

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

//架构2

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

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

我尝试使用查找函数通过相同的文件名(特别是ip)连接这两个模式。

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

在结果中,我得到了IP地址,但geo字段为空。

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

e5njpo681#

试试这个:

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

Playground.

ivqmmu1c

ivqmmu1c2#

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);
      }
    });

相关问题