Javascript MEAN.JS Mongoose在中间件中填充不起作用
概要 我将其用作web应用程序的完整web堆栈解决方案,用于列出用户的文章。它与默认情况下MEAN.JS提供的示例非常相似 问题 当我调用文章列表Javascript MEAN.JS Mongoose在中间件中填充不起作用,javascript,node.js,mongodb,mongoose,meanjs,Javascript,Node.js,Mongodb,Mongoose,Meanjs,概要 我将其用作web应用程序的完整web堆栈解决方案,用于列出用户的文章。它与默认情况下MEAN.JS提供的示例非常相似 问题 当我调用文章列表http://localhost:3000/articles,结果集包含与每篇文章相关联的用户电子邮件和用户名(通过Mongoose填充功能)。但是当我检索到一篇文章http://localhost:3000/articles/1234567890,用户信息与文章无关 我尝试使用mongoose relationsip插件,并将toObject:{vi
http://localhost:3000/articles
,结果集包含与每篇文章相关联的用户电子邮件和用户名(通过Mongoose填充功能)。但是当我检索到一篇文章http://localhost:3000/articles/1234567890
,用户信息与文章无关
我尝试使用mongoose relationsip插件,并将toObject:{virtuals:true},toJSON:{virtuals:true}
添加到文章模型中。两者都不起作用
有关更多详细信息,我已经关联了控制器、路由器和文章对象的模型
型号
为了简单起见,我只为每个对象包含了必要的属性。基本上,我有一个article对象和一个user对象(顺便说一句:我使用的是MEAN.JS提供的相同示例)
articles.server.model.js
"严格使用",
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
relationship = require("mongoose-relationship");
/**
* Article Schema
*/
var ArticleSchema = new Schema({
body: {
type: String,
default: '',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User',
childPath:"articles"
},
viewCount: {
type: Number,
optional: true,
},
comments:[{
type:Schema.ObjectId,
ref:"Comment"
}],{
strict: true,
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
ArticleSchema.plugin(relationship, { relationshipPathName:'user' });
mongoose.model('Article', ArticleSchema);
articles.server.routes.js
articles.server.controller.js
任何帮助都将不胜感激
谢谢。您的文章中间件似乎没有将文章添加到
req
。在调用next()
之前添加此行:
在本部分中,您没有将结果分配给req
exports.articleByID = function(req, res, next, id) {
Article.findById(id).populate('user', 'displayName email').exec(function(err, article) {
if (err) return next(err);
if (!article) return next(new Error('Failed to load article ' + id));
req.article = article; //THIS PART IS MISSING
next();
});
};
因此,当您按id阅读一篇文章时,您可以从req.article
exports.read = function(req, res) {
res.json(req.article);
};
它不起作用。似乎无法在中间件上覆盖req.article,或者它可能在next()之后被实际覆盖。不确定,请尝试此
article.findById(id)。填充('user','displayName')。填充('email')。exec(…
req.article = article;
exports.articleByID = function(req, res, next, id) {
Article.findById(id).populate('user', 'displayName email').exec(function(err, article) {
if (err) return next(err);
if (!article) return next(new Error('Failed to load article ' + id));
req.article = article; //THIS PART IS MISSING
next();
});
};
exports.read = function(req, res) {
res.json(req.article);
};