猫鼬按参考字段查找

时间:2019-12-02 11:57:46

标签: node.js mongoose

我有这样的频道架构:

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

谢谢

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

由于您没有从通道架构到反馈架构的任何引用,因此可以使用猫鼬的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
    }
]