链接 2 个 Mongoose 集合

Linking 2 Mongoose collections

我正在尝试建立一个简单的网站,经过身份验证的用户(作者)可以在其中撰写和 post 故事。 我有一个 Author 集合和一个 Story 集合,我正在尝试在两个集合之间创建链接。我正在使用猫鼬和 populate/ref 方法。我可以成功地显示包含作者信息的故事或故事列表,但在显示作者简介时,我真的很难将故事列表附加到作者。我想要的是确保在访问作者个人资料页面时,用户可以看到他们的故事列表。

我正在尝试使用 populate/ref 方法来实现将显示作者故事列表 (storyList) 的数组,但该数组一直是空的。在显示作者个人资料页面时,我首先使用了 findById 函数,但了解到这似乎不适用于 populate。所以我现在使用 findOne 函数,但结果相同。

这是我的作者合集:

const mongoose = require('mongoose');

const authorSchema = mongoose.Schema({
  userName: {
    type: String,
    required: true
  },
  firstName: String,
  lastName: String,
  authorImage: {
    type: String
  },
  emailAddress: {
    type: String,
    required: true,
    unique: true,
    match: /^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  },
  password: {
    type: String,
    required: true
  },
  storyList: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Story'
  }]
});

module.exports = mongoose.model('Author', authorSchema, 'authors');

这是我显示作者个人资料页面的路径:

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const Author = require('../models/author');

exports.authors_get_one = (req, res, next) => {
  const username = req.params.userName;
  Author.findOne(username)
    .select("_id userName firstName lastName emailAddress password authorImage storyList")
    .populate('storyList')
    .exec()
    .then(doc => {
      console.log("From database", doc);
      if (doc) {
        res.status(200).json({
          author: doc,
        });
      } else {
        res.status(404).json({
          message: 'No valid entry found for provided ID'
        });
      }
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
}

这是我的故事架构

const mongoose = require('mongoose');

const storySchema = mongoose.Schema({
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Author',
  },
  title: {
    type: String,
  },
  text: {
    type: String,
  },
  language: {
    type: String,
  },
  published: {
    type: Boolean,
    default: false
  }
});

module.exports = mongoose.model('Story', storySchema, 'stories');

这是我创作故事的路线:

const mongoose = require('mongoose');
const Story = require('../models/story');
const Author = require('../models/author');

exports.stories_createOne = (req, res, next) => {
  const story = new Story({
    title: req.body.title,
    text: req.body.text,
    language: req.body.language,
    author: req.body.author
  });
  story
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Story publiée !",
        createdStory: {
          _id: result._id,
          title: result.title,
          text: result.text,
          language: result.language,
          author: result.author,
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
}

从我找到的文档中,我看不出我做错了什么。我在这里错过了什么吗? populate 方法是否不足以完成我的故事列表 (storyList)?我什至应该在我的代码中的其他地方做些什么吗?

您的 storyList 数组保持为空的原因是您没有在创建故事后将故事引用推入 author.storyList 数组。 Source.

解决这个问题的简单方法是在创建故事的路径中执行类似的操作:

exports.stories_createOne = (req, res, next) => {
  const story = new Story({
    title: req.body.title,
    text: req.body.text,
    language: req.body.language,
    author: req.body.author
  });
  story
    .save()
    .then(result => {
      console.log(result);
      // Push the story id into the author.storyList array
      Author
        .update(
          { _id: req.body.author }, 
          { $push: { storyList: result.toJSON()._id } }
         )
        .then(() => {
          // send response here
        })
    })
    .catch(err => {
      // Handle Error
    });
}