Node.js: обновление документа с помощью Mongoose

1

Я пытаюсь обновить приглашение, когда запрашиваемый пользователь регистрируется. Приглашение имеет свойство auth, которое представляет собой вложенный объект, который сам имеет свойство с ключом "used". Я просто пытаюсь явно объявить значение true и сохранять, используя async/await. Но это не обновление. Есть лучший способ сделать это?

Моя функция:

exports.invitedSignup = async (req, res, next) =>
{
    const { firstName, lastName, company, password, email, companyCode, token } = req.body;
    console.log(email);
    try
    {
        const user = await User.findOne({ email });
        const invitation = await Invitation.findOne({ email }).sort({ field: 'asc', _id: -1 }).limit(1);
        if (user) { return res.status(422).send({ error: "User is already registered" }); };
        if (!invitation) { return res.status(422).send({ error: "No invitation on record" }); };
        if (token !== invitation.auth.token)
        {
            return res.status(422).send({ error: "Something has gone wrong, please sign up again" });
        }
        try
        {
            invitation.auth.used = true;
            const updateInvitation = await invitation.save();
            console.log("authorization: " + invitation.auth.used);
        } catch (e)
        {
            return next(e);
        }
        try
        {
            const saveUser = new User({
                firstName: firstName,
                lastName: lastName,
                email: req.body.email,
                password: password,
                company: company,
                companyCode: companyCode,
                role: 1,
                auth: { used: true }
            });

            const newUser = await saveUser.save(); 
            const { email, firstname, lastname } = newUser;
            res.json({ token: tokenForUser(newUser), email, firstName, lastName });
        }
        catch (e)
        {
            return next(e);
        }
    }
    catch (e)
    {
        return next(e);
    }
};

Схема приглашения:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');

//define model
const invitationSchema = new Schema({
    email: { type: String, unique: true, lowercase: true, unique: true },
    inviter: String,
    company: String,
    companyCode: String,
    created: Date,
    auth: {
        token: String,
        used: Boolean,
        expires: Date,
    }
});

invitationSchema.pre('save', function (next)
{
    const invitation = this;

    bcrypt.genSalt(10, (err, salt) =>
    {
        const tomorrow = new Date();
        invitation.created = tomorrow;
        tomorrow.setDate(tomorrow.getDate() + 1);
        if (err) { return next(err); };
        invitation.auth = { token: salt, used: 0, expires: tomorrow };
        next();
    });
});


//create model class
const ModelClass = mongoose.model('invitation', invitationSchema);

//export model
module.exports = ModelClass;
  • 1
    Можете ли вы обновить свой вопрос, чтобы включить определение схемы для Invitation ?
  • 0
    да я его обновил
Показать ещё 3 комментария
Теги:
mongoose

1 ответ

0

http://mongoosejs.com/docs/schematypes.html#mixed

person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved
  • 0
    Но я никогда не объявлял свой тип схемы смешанным. Почему он это делает?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню