【问题标题】:How to push a sub document inside an array in mongoose?如何在猫鼬的数组中推送子文档?
【发布时间】:2020-07-10 01:27:54
【问题描述】:

我正在尝试在主题中添加一系列步骤。但每次我发出一个帖子请求。它只存储一个带有 _id 的空数组。 这是我的模型:

const mongoose = require('mongoose');
//const Step = require('./Step');

const StepSchema = mongoose.Schema({
    title: String,
    status: String,
    date: {
        type: Date,
        default: Date.now
    }
});

const TopicSchema = mongoose.Schema({
    name: String,
    description: String,
    steps: [StepSchema],
    date: {
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('Topic', TopicSchema);

这是我的 router.js:

const express = require('express');
const router = express.Router();
const Topic = require('../models/Topic');

router.post('/', async (req, res) => {
    const topic = new Topic({
        name: req.body.name,
        description: req.body.description,
    });
    topic.steps.push({
        title: req.body.title,
        status: req.body.status
    })
    try {
        const saveTopic = await topic.save();
        res.json(saveTopic);
    } catch (err) {
        res.json({ message: err });
    }
});

module.exports = router;

这是我的邮递员请求:

{
    "name": "t",
    "description": "y",
    "steps": {
        "title": "a",
        "status": "b"
    }
}

提前致谢。

【问题讨论】:

    标签: javascript arrays node.js express mongoose


    【解决方案1】:

    在您的 POSTMAN 请求中,标题和状态包含在 steps 对象中。

    你需要做的:

    topic.steps.push({
        title: req.body.steps.title,
        status: req.body.steps.status
    });
    

    代替:

    topic.steps.push({
        title: req.body.title,
        status: req.body.status
    });
    

    【讨论】:

    • 非常感谢。我还不得不更改我的邮递员请求。 { "name": "t", "description": "y", "steps": { "title": "a", "status": "b" } } 再次感谢!
    猜你喜欢
    • 2015-06-08
    • 2016-06-05
    • 2017-01-11
    • 2018-05-17
    • 2020-03-17
    • 2015-06-26
    • 2016-01-29
    • 1970-01-01
    • 2016-01-24
    相关资源
    最近更新 更多