【问题标题】:Linking 2 Mongoose collections链接 2 个 Mongoose 集合
【发布时间】:2020-05-27 10:38:51
【问题描述】:

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

我正在尝试使用 populate/ref 方法来完成将显示故事作者列表 (storyList) 的数组,但该数组始终为空。在显示作者个人资料页面时,我首先使用了 findById 函数,但了解到这似乎不适用于填充。所以我现在使用 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)?我应该在我的代码中的其他地方做些什么吗?

【问题讨论】:

  • 你的Story 架构怎么样?
  • 嗨@whoami,感谢您的评论,我在最初的问题中添加了故事模式和创建故事的路线
  • 你能不能把这个mongoose.model('Story', storySchema, 'stories') 改成mongoose.model('Story', storySchema, 'Story') 并在Author 上试试你的findOne 查询..
  • 我刚刚尝试过但结果相同.. :/

标签: arrays node.js mongodb mongoose populate


【解决方案1】:

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
    });
}

【讨论】:

  • 太棒了,它确实有效!我之前实际上尝试过这个 $push 方法,但没有正确使用它。非常感谢您的帮助!
猜你喜欢
  • 2021-05-21
  • 2018-09-15
  • 2022-12-03
  • 2016-01-29
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多