繁体   English   中英

Mongoose 按参考字段查找

[英]Mongoose find by reference field

我有这样的频道架构:

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);

这是反馈模式:

const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});

如何按频道名称查找反馈?

Feedback.find({channelId.name : 'something'})

谢谢

由于您没有从通道架构到反馈架构的任何参考,因此您可以使用mongoose 的 populate-virtuals功能。

所需的更改如下所示:

1-) 像这样替换您的频道架构以使用虚拟填充:

const mongoose = require("mongoose");

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  },
  {
    toJSON: { virtuals: true }
  }
);

// Virtual populate
channelSchema.virtual("feedbacks", {
  ref: "feedback",
  foreignField: "channelId",
  localField: "_id"
});

module.exports = mongoose.model("channel", channelSchema);

2-) 使用以下查询查找给定频道名称的反馈:

请注意,我在查询中硬编码了频道名称,您可以从请求正文或请求查询或请求参数中读取它。

router.get("/feedback", async (req, res) => {
  const result = await Channel.findOne({ name: "Channel 1" }).populate({
    path: "feedbacks"
  });

  res.send(result);
});

响应将是这样的:

[
  {
    "_id": "5de5509476a9c34048c1d23d",
    "name": "Channel 1",
    "__v": 0,
    "feedbacks": [
      {
        "_id": "5de5512d7d87de2d4c6b38d2",
        "channelId": "5de5509476a9c34048c1d23d",
        "__v": 0
      },
      {
        "_id": "5de551357d87de2d4c6b38d3",
        "channelId": "5de5509476a9c34048c1d23d",
        "__v": 0
      }
    ],
    "id": "5de5509476a9c34048c1d23d"
  }
]

或者,如果您只对反馈感兴趣,您可以通过result.feedbacks访问它们:

router.get("/feedback", async (req, res) => {
  const result = await Channel.findOne({ name: "Channel 1" }).populate({
    path: "feedbacks"
  });

  res.send(result.feedbacks);
});

这会给你一系列这样的反馈:

[
    {
        "_id": "5de5512d7d87de2d4c6b38d2",
        "channelId": "5de5509476a9c34048c1d23d",
        "__v": 0
    },
    {
        "_id": "5de551357d87de2d4c6b38d3",
        "channelId": "5de5509476a9c34048c1d23d",
        "__v": 0
    }
]

您不能在不存在的对象上查询属性,我建议首先查询通道,获取 id 并从那里进行查找。

const channel = await Channel.findOne({ name });
const feedback = await Feedback.find({ channelId: channel._id })

您可以使用插件mongoose-find-by-reference

Step.1 安装

npm i -S mongoose-find-by-reference

npm 链接Github 链接

Step.2 plugin()插件

const mongoose = require("mongoose");

// Require mongoose-find-by-reference
const { MongooseFindByReference } = require('mongoose-find-by-reference');

await mongoose.connect("mongodb://localhost:27017/test")

const channelSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      unique: true
    }
  }
);


const feedbackSchema = new mongoose.Schema({
  channelId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "channel",
    require: true
  }
});

// Execute function plugin() on schema with Reference paths
feedbackSchema.plugin(MongooseFindByReference);


const Channel= mongoose.model('channel', channelSchema );
const Feedback= mongoose.model('feedback', feedbackSchema );

Step.3 随便用!

const { _id } = await Channel.create({ name: "C" })

await Feedback.create({channelId : _id})

/** Its conditions will be auto automatically replaced with :
{
  channelId: {
    $in: [
      /* ObjectIDs for Eligible channels */
    ],
  },
}
 */
const findResult = await Feedback.find({channelId.name : 'C'})

使用populate方法查询

try {
  const data = await feedBack.find(...).populate({ path: 'channel', match: { id: 'xxx' }).exec();
} catch (err) {
  console.log(err);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM