我不能应付猫鼬的人口

时间:2018-10-25 20:24:38

标签: node.js mongodb express mongoose

当我在控制台中尝试登录“ category”时,我认为这不是填充类别的原因 “ ReferenceError:类别未定义”。对我来说,就像在文档中一样,但正如我们所看到的那样。有人可以告诉我哪里出了问题吗?

// model / Category.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
 const CatSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    }
});
 mongoose.model("categories", CatSchema, "categories");

model / Story.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
     const StorySchema = new Schema({
    title: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    category: {
        type: Schema.Types.ObjectId,
        ref: "categories"
    }

});
     mongoose.model("stories", StorySchema, "stories");

routes / stories.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Category = mongoose.model('categories');
const Story = mongoose.model('stories');
     router.get('/add', (req, res) => {
    Story.find()
        .populate('category',  'title')
        .then(stories => {
            res.render('stories/add', {
                stories: stories
            });
        });
});

2 个答案:

答案 0 :(得分:1)

Query.prototype.populate()返回一个Query对象,您需要在该对象上运行.exec(),请尝试以下操作:

Story.find({})
    .populate('category',  'title')
    .exec()
    .then(stories => {
        res.render('stories/add', {
            stories: stories
        });
});

答案 1 :(得分:0)

我要如何使用它存在问题。代码正常工作