猫鼬问题添加子级到文档

时间:2019-02-20 09:37:13

标签: node.js mongodb mongoose

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

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

婚礼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;

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

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

1 个答案:

答案 0 :(得分:2)

我认为问题在于您没有创建新来宾,也没有保存婚礼: (感谢@ 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);
});

如果您需要更多信息:Constructing Documents in Mongoose - Documentation