繁体   English   中英

我不能应付猫鼬的人口

[英]I can't handle populate in 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");

模型/ 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");

路线/ 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
            });
        });
});

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

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

我要如何使用它存在问题。 代码有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM