链接2个猫鼬收藏集

时间:2020-02-11 23:10:25

标签: arrays node.js mongodb mongoose populate

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

我正在尝试使用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
      });
    });
}

从找到的文档中,我看不到我在做什么错。我在这里想念什么吗?填充方法不足以满足我的故事列表(storyList)吗?我该在代码中的其他地方执行什么操作吗?

1 个答案:

答案 0 :(得分:0)

您的storyList数组保持为空的原因是,您没有在创建故事后将故事ref推送到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
    });
}