猫鼬找到带有id的子文档,CoreMongooseArray vs DocumentArray

mongoose find subdocs with id, CoreMongooseArray vs DocumentArray

我得到了两个方案之间的关系,为了简单起见,我们称之为 parent => children.

const ChildScheme = new mongoose.Schema(
    {
        name: { type: String, required: true },
    },
    {
        timestamps:true
    });

const child = mongoose.model("Child", Child);

const ParentScheme = new mongoose.Schema(
    {
        name: { type: String, required: true },
        children: [{type: mongoose.Schema.Types.ObjectId, ref: Child, autopopulate: true}],
    },
    {
        timestamps:true
    });

现在我想通过 child 的 ID 从特定的 parent 获取特定的 child。

我试过的是:

models.Parent.findById('parent_obj_id')
    .then((parent) => {
        let child = parent.children.id('child_id')
    });

然而这不起作用,children 是 CoreMongooseArray 类型,它没有函数 id。

我搜索了一下源代码,我可以看到从 CoreMongooseArray 扩展而来的 class CoreDocumentArray 确实具有该功能。

为什么我得到一个 CoreMongooseArray?这行不通吗,因为实际上是猫鼬

当我执行以下命令时:

models.Parent.findById('parent_obj_id')
    .then((parent) => {
        console.log(parent);
    });

我会收到这样的回复:

{ children:
   [ { name: [],
       _id: 5dbd9723533e204ab91ccee5,
       name: 'peter',
       createdAt: 2019-11-02T14:48:03.763Z,
       updatedAt: 2019-11-02T14:48:03.763Z,
       __v: 0 } ],
  _id: 5dbd9723533e204ab91ccee3,
  name: 'Walter',
  createdAt: 2019-11-02T14:48:03.596Z,
  updatedAt: 2019-11-02T14:48:03.806Z,
  __v: 3 }

找到父项后,您可以使用 javascript 数组查找访问特定的子项,如下所示:

models.Parent.findById("parent_obj_id").then(parent => {
  let child = parent.children.find(c => c._id.toString() === "child_id");
  console.log(child);

  //todo: send response
});

我做了一个像这样的简单演示:

(我猜你正在使用 https://www.npmjs.com/package/mongoose-autopopulate 包来实现自动填充功能)

父模型(团队):

const mongoose = require("mongoose");

const teamSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  players: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Player",
      autopopulate: true
    }
  ]
});

teamSchema.plugin(require("mongoose-autopopulate"));

const team = mongoose.model("Team", teamSchema);
module.exports = team;

童模:(玩家)

const mongoose = require("mongoose");

const playerSchema = new mongoose.Schema({
  name: String
});

const player = mongoose.model("Player", playerSchema);
module.exports = player;

我有3个这样的玩家:

[
    {
        "_id": "5dbdb7cf0101fb08b434a576",
        "name": "player 1",
        "__v": 0
    },
    {
        "_id": "5dbdb7d80101fb08b434a577",
        "name": "player 2",
        "__v": 0
    },
    {
        "_id": "5dbdb7e00101fb08b434a578",
        "name": "player 3",
        "__v": 0
    }
]

我有 1 支球队有这样的 3 名球员:

[
    {
        "players": [
            "5dbdb7cf0101fb08b434a576",
            "5dbdb7d80101fb08b434a577",
            "5dbdb7e00101fb08b434a578"
        ],
        "_id": "5dbdb80d0101fb08b434a579",
        "name": "team 1",
        "__v": 0
    }
]

要获取球队 1 的球员 1 信息,我使用以下路线:

router.get("/team/:teamId/:playerId", (req, res) => {
  const { teamId, playerId } = req.params;

  Team.findById(teamId).then(team => {
    const player = team.players.find(p => p._id.toString() === playerId);
    res.send(player);
  });
});

结果是:

{
    "_id": "5dbdb7cf0101fb08b434a576",
    "name": "player 1",
    "__v": 0
}