【发布时间】: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