0

参考https://mongoosejs.com/docs/populate.html#checking-populated给出的 Mongoose url populate 示例,两个 Schema 之间似乎存在双向关系。例如,如果我只有一种方式的关系怎么办(使用相同的模式示例,但 Person 模式没有Story ref )

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const personSchema = Schema({
  name: String,
  age: Number
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);

如何返回如下所示的 GET Story 输出:

{
  author :{
    name: "Bla bla bla",
    age: 30
  }
  title : "ABC Story"
}

我现在总是得到这个:

{
  author :34235245453
  title : "ABC Story"
}
4

2 回答 2

1

我不确定这是否是一个好的做法,但您可以按如下方式实现

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const personSchema = Schema({
  name: String,
  age: Number
});

const storySchema = Schema({
  author: Schema.Types.ObjectId, //modified by just defining the type
  title: String
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);

填充时,

SOMETHING.find()
.populate({
   'path':'author',
   'model':'Person'
});
于 2020-02-07T06:25:33.963 回答
1

我认为您混淆了填充()函数和填充()函数。

为了能够检索故事的作者信息,我们需要像这样使用填充:

router.get("/stories/:id", async (req, res) => {
  const result = await Story.findById(req.params.id).populate("author");
  res.send(result);
});

假设我们有这个人:

{
    "_id": "5e3c63ba3a178830dc497a00",
    "name": "Name1",
    "age": 33,
    "__v": 0
}

用户的这个故事:

{
    "_id": "5e3c63e93a178830dc497a02",
    "author": "5e3c63ba3a178830dc497a00",
    "title": "Story1",
    "__v": 0
}

当我们向我们的路由发送 get 请求时,结果将是这样的 ( http://.../stories/5e3c63f33a178830dc497a02)

{
    "_id": "5e3c63e93a178830dc497a02",
    "author": {
        "_id": "5e3c63ba3a178830dc497a00",
        "name": "Name1",
        "age": 33,
        "__v": 0
    },
    "title": "Story1",
    "__v": 0
}

要获取所有带有作者信息的故事,我们可以使用 find() 方法,如下所示:

router.get("/stories", async (req, res) => {
  const result = await Story.find().populate("author");
  res.send(result);
});
于 2020-02-06T19:13:04.683 回答