首页 > 解决方案 > 我填充了一个 Mongoose 模型,但是当我稍后引用它时它没有填充

问题描述

我正在为一个具有 CRUD 功能的简单 Web 应用程序编写代码。我试图添加一个评论部分,并为“公式”模式提出了一个模型。您可以将“公式”视为等同于“博客文章”。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const commentModel = require('./comment.js');

const formulaSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    creator: {
        type: String,
        required: true
    },
    formula: {
        type: String,
        required: true
    },
    comments: [ 
        { 
            type: Schema.Types.ObjectId, 
            ref: 'Comment' 
        } 
    ]
})

const formulaModel = mongoose.model('formula', formulaSchema);

module.exports = formulaModel;

上面显示的代码适用于公式模型。

const Schema = mongoose.Schema;

const commentSchema = new Schema({
    name: {
        type: String,
        required: false
    },
    body: {
        type: String,
        required: true
    },
    rating: {
        type: Number,
        enum: [1, 2, 3, 4, 5]
    }
})

const commentModel = mongoose.model('Comment', commentSchema);

module.exports = commentModel;

上面显示的代码用于注释模型。

每当我添加评论时,我都会将其添加到公式模型中,然后填充它。

const express = require('express');
const router = express.Router();
const {formulaSchema, commentSchema} = require('../schemas.js');
const formulaModel = require('../models/formula.js');
const commentModel = require('../models/comment.js');
const AppError = require('../AppError');

const wrapAsync = require('../functions/wrappers/wrap');
const verifyID = require('../functions/validations/verifyID');


const verifyComment = (req, res, next) => {
    const { error } = commentSchema.validate(req.body);
    if(error) {
        const msg = error.details.map(el => el.message);
        throw new AppError(400, msg);
    } else {
        next();
    }
}

router.post('/:id/comments', verifyComment, wrapAsync(async function(req, res, next) {
    const { id } = req.params;
    const theFormula = await formulaModel.findById(id);
    const comment = new commentModel(req.body.comment);
    await theFormula.comments.push(comment);
    await theFormula.populate('comments');
    await theFormula.save();
    await comment.save();
    
    //console.log(theFormula.comments[0].name);
    
    res.redirect(`/details/${id}`);
}))

module.exports = router;

通过 console.logging,我认识到模型已正确填充:

{
  _id: new ObjectId("613f4ef3677593f9173e60c5"),
  name: 'The Ultimate Addition',
  creator: 'Anonymous',
  formula: '1+1=2',
  comments: [
    {
      _id: new ObjectId("613f4f09677593f9173e60cb"),
      name: 'The First Comment',
      body: '#1. Do not comment bullshit.',
      rating: 1,
      __v: 0
    },
    {
      _id: new ObjectId("613f4fcff98c95a4af3f6722"),
      name: 'The Second Comment',
      body: '222222222222',
      rating: 2,
      __v: 0
    },
    {
      _id: new ObjectId("613f50f24d97ad45daa850b2"),
      name: 'The Third Comment',
      body: '33333333333',
      rating: 3,
      __v: 0
    },
    {
      _id: new ObjectId("613f52f9c0b6ad6247ad7d6a"),
      name: 'The Fourth Comment',
      body: '4444$$$$',
      rating: 3,
      __v: 0
    }
  ],
  __v: 5
}

但是,当我稍后访问它时,它似乎没有被填充:

const express = require('express');
const router = express.Router();
const {formulaSchema, commentSchema} = require('../schemas.js');
const formulaModel = require('../models/formula.js');

const wrapAsync = require('../functions/wrappers/wrap');
const verifyID = require('../functions/validations/verifyID');


router.get('/:id', verifyID, wrapAsync(async (req, res, next) => {
    const {theFormula} = res.locals;
    // console.log(theFormula);
    res.render('detail', {theFormula});
}))

module.exports = router;

通过 console.logging,我得到如下结果:

{
  _id: new ObjectId("613f4ef3677593f9173e60c5"),
  name: 'The Ultimate Addition',
  creator: 'Anonymous',
  formula: '1+1=2',
  comments: [
    new ObjectId("613f4f09677593f9173e60cb"),
    new ObjectId("613f4fcff98c95a4af3f6722"),
    new ObjectId("613f50f24d97ad45daa850b2"),
    new ObjectId("613f52f9c0b6ad6247ad7d6a"),
    new ObjectId("613f531c5065ca83ad450dea")
  ],
  __v: 5
}

为什么我的模型没有填充?我的意思是,它确实通过评论部分保存了所有其他更改。

标签: mongoosemongoose-schemamongoose-populate

解决方案


推荐阅读