首页 > 解决方案 > 将子子项添加到文档中的猫鼬问题

问题描述

我是 MongoDB 和 Node JS 的新手。我在 Mongo 的文档中添加孩子时遇到问题。

该数据库有一个集合 cald 婚礼,并且在每个文档中是一个婚礼。婚礼文件还包含客人,如下所示:

婚礼 1 - 客人 1 - 客人 2

婚礼 2 - 客人 3 - 客人 4 等

现在我在为婚礼添加客人时遇到了麻烦。这是我的模型:

const Joi = require('joi');
const mongoose = require('mongoose');

const guestSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    surname: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    plz: {
        type: String,
        minlength: 2,
        maxlength: 10
    },
    confirmed: { type: Boolean, default: false },
    type: Number,
    questlink_id: Number,
    confirmedDate: Date,
    hasExtraTable: Boolean
});


const weddingSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    nameA: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    nameB: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    surnameA: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    surnameB: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    location: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 255
    },
    street: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
    },
    streetnumber: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 50
    },
    plz: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10
    },
    city: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
    },
    country: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
    },
    telefon: {
        type: String,
        minlength: 5,
        maxlength: 50
    },
    email: {
        type: String,
        minlength: 5,
        maxlength: 255
    },
    payed: { type: Boolean, default: false },
    user_id: {
        type: String,
        required: true
    },
    weddingDate: {
        type: Date
    },
    registerUntilDate: {
        type: Date
    },
    tableSize: {
        type: Number
    },
    link: {
        type: String,
        unique: true,
        default: null
    },
    guest: [ guestSchema ]
});

const Wedding = mongoose.model('wedding',weddingSchema);

function validateWedding(wedding) {
    const schema = {
        title: Joi.string().min(2).max(255).required(),
        nameA: Joi.string().min(5).max(50).required(),
        surnameA: Joi.string().min(5).max(50).required(),
        nameB: Joi.string().min(5).max(50).required(),
        surnameB: Joi.string().min(5).max(50).required(),
        location: Joi.string().min(5).max(50).required(),
        street: Joi.string().min(5).max(50).required(),
        streetnumber: Joi.string().min(5).max(50).required(),
        city: Joi.string().min(5).max(50).required(),
        plz: Joi.string().min(5).max(50).required(),
        country: Joi.string().min(5).max(50).required(),
    };

    return Joi.validate(wedding, schema);
}

function validateGuest(guest) {
    const schema = {
        name: Joi.string().min(5).max(50).required(),
        surname: Joi.string().min(5).max(50).required(),
        plz: Joi.string().min(5).max(50).required()
    };

    return Joi.validate(guest, schema);
}
exports.guestSchema = guestSchema;
exports.weddingSchema = weddingSchema;
exports.Wedding = Wedding;
exports.validateWedding = validateWedding;
exports.validateGuest = validateGuest;

这是我的路由器,或者至少是重要的部分:

const auth = require('../middleware/auth');
const {Wedding, validateWedding, validateGuest, guestSchema} = require('../models/wedding');
const {User} = require('../models/user');
const _ = require('lodash');
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();


router.get('/:id/guests', auth, async (req, res) => {
    const weddings = await Wedding.findById(req.params.id);
    if(weddings.user_id != req.user._id)
        res.status(400).send('This is not your wedding');
    res.send(weddings.guest);
});

router.post('/:id/guests', auth, async (req, res) => {
    const { error } = validateGuest(req.body);
    if (error) return res.status(400).send(error.details[0].message);

    const weddings_1 = await Wedding.findById(req.params.id);
    if(weddings_1.user_id != req.user._id)
        res.status(400).send('This is not your wedding');

    const guest = mongoose.model('Guest',guestSchema);
    guest.name = req.body.name;
    guest.surname = req.body.surname;
    guest.plz = req.body.plz;

    let weddings = await Wedding.findByIdAndUpdate(req.params.id,{
        guest: [ {
            name : req.body.name,
            surname: req.body.surname,
            plz: req.body.plz
        } ]
    });

    // weddings.guest.push(guest);

    res.send(weddings);
});

module.exports = router;

我试图将数据推送到数据库中,并尝试更新整个文档。

如果有人有任何建议,谢谢!

标签: node.jsmongodbmongoose

解决方案


我认为问题在于您没有创建新客人,也没有保存婚礼:(感谢@ykit9 的更正)

const Guest = mongoose.model('Guest', guestSchema);
const newGuest = new Guest({
        name : req.body.name,
        surname: req.body.surname,
        plz: req.body.plz
    });
newGuest.save();

Wedding.findOne({_id: req.params.id}, (err, foundWedding)=>{
    foundWedding.guest.push(newGuest);
    foundWedding.save();

    res.send(foundWedding);
});

如果您需要更多信息:在 Mongoose 中构建文档 - 文档


推荐阅读