意思是.JS中间件中的猫鼬填充不起作用

MEAN.JS Mongoose Populate in middleware does not work

本文关键字:填充 不起作用 JS 中间件 意思是      更新时间:2023-09-26

概要

我正在使用 MeanJS 作为 Web 应用程序的完整 Web 堆栈解决方案来列出用户的文章。它与 MEAN.JS 默认提供的示例非常相似。

问题

当我调用文章列表http://localhost:3000/articles时,结果集具有与每篇文章关联的用户电子邮件和用户名(通过猫鼬填充功能)。但是当我检索单个文章http://localhost:3000/articles/1234567890时,用户信息与文章无关。

我尝试使用猫鼬关系插件,并将toObject: { virtuals: true }, toJSON: { virtuals: true }添加到文章模型中。两者都不起作用。

有关更多详细信息,我已关联了控制器,路由器和文章对象的模型。

模型

为简单起见,我只包含每个对象的必要属性。基本上,我有一个文章对象和一个用户对象(顺便说一句:我正在使用 MEAN.JS 提供的相同示例)。

文章.服务器.模型.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);

文章.服务器.路由.js

'use strict';
/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users.server.controller'),
    articles = require('../../app/controllers/articles.server.controller');
module.exports = function(app) {
    // Article Routes
    app.route('/articles')
        .get(articles.list)
        .post(users.requiresLogin, articles.create);
    app.route('/articles/:articleId')
        .get(articles.read)
        .put(users.requiresLogin, articles.hasAuthorization, articles.update)
        .delete(users.requiresLogin, articles.hasAuthorization, articles.delete);
    // Finish by binding the article middleware
    app.param('articleId', articles.articleByID);
};

Articles.server.controller.js

'use strict';
/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    errorHandler = require('./errors.server.controller'),
    Article = mongoose.model('Article'),
    db=require('./databaseoperations'),
    _ = require('lodash');
/**
 * Show the current article
 */
exports.read = function(req, res) {
    res.json(req.article);
};
/**
 * List of Articles
 */
exports.list = function(req, res) {
    Article.find().populate('user', 'displayName email').exec(function(err, articles) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.json(articles);
        }
    });
};
/**
 * Article middleware
 */
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));
        next();
    });
};

任何帮助将不胜感激。

谢谢。

看起来您的文章中间件没有将文章添加到req中。在调用next()之前添加此行:

req.article = article;

在这一部分中,您没有将结果分配给 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);
};