【问题标题】:Node.js: Updating a document with MongooseNode.js:使用 Mongoose 更新文档
【发布时间】:2018-04-18 16:26:14
【问题描述】:

我正在尝试在受邀用户注册时更新邀请。邀请有一个 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;

【问题讨论】:

  • 您能否更新您的问题以包含Invitation 的架构定义?
  • 是的,我更新了
  • 您的预保存中间件总是覆盖文档的auth 子文档,不是吗?
  • @JohnnyHK 啊,这确实有道理。所以我应该重写它以仅在邀请没有身份验证部分时运行,对吗?
  • 无论您的业务逻辑需要什么。

标签: javascript node.js mongodb mongoose


【解决方案1】:

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

person.anything = { x: [3, 4, { y: "changed" }] };
person.markModified('anything');
person.save(); // anything will now get saved

【讨论】:

  • 但我从未将我的 Schema 类型声明为混合。为什么会这样?
猜你喜欢
  • 2017-09-22
  • 1970-01-01
  • 2011-12-04
  • 2012-10-27
  • 1970-01-01
  • 2017-06-06
  • 2017-08-13
  • 1970-01-01
相关资源
最近更新 更多