简体   繁体   English

Mongoose 填充。 是否可以通过参数链接 collections

[英]Mongoose populate. Is it possible to link collections by their parameter

const mongoose = require('mongoose');
const { Schema } = mongoose;

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

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

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

Story.
  findOne({ title: 'Casino Royale' }).
  populate('author')

Tell me what you need to add to link two collections by the userId parameter告诉我你需要添加什么通过userId参数链接两个collections

the populate method have some params, as the path and select .填充方法有一些参数,如pathselect the path is the most important one, it's where you determine what field of you model you're trying to populate. path是最重要的,它是您确定要填充 model 的哪个字段的地方。

The populate method use the mongoose default generated _id for searches. populate方法使用 mongoose 默认生成的_id进行搜索。 So your field userId will not work in this case.因此,您的字段userId在这种情况下将不起作用。 If you want to use a custom ID for your models, you should add the attribute _id to your model and pass it in the creation of a document.如果你想为你的模型使用自定义 ID,你应该将属性_id添加到你的 model 并在创建文档时传递它。

So, you're probably looking for this:所以,你可能正在寻找这个:

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

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

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

await Person.create({
  _id: 1,
  name: 'Andreas'
});

await Story.create({
  author: 1,
  title: 'Casino Royale'
});

var story = await Story
  .findOne({ title: 'Casino Royale' })
  .populate({
    path: 'author',
    select: 'name',
  });

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

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