在Moongose模式中更新用户字段时,如何避免用户验证?

时间:2019-06-16 17:12:32

标签: mongodb mongoose

我有两个模式,User和Post。

添加帖子时,我希望在用户架构中添加对该帖子的引用。问题是我使用预保存的钩子进行验证,并且由于数据库或用户名中已经存在电子邮件,因此不允许我保存帖子。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: {
    type: String,
    required: true,
    },
    username: {
    type: String,
    required: true,
        },
        password: {
            type: String,
            required: true,
        },
        salt: {
            type: String,
            required: true,
        },
        active: {
            type: Boolean,
            default: true,
        },
        token: {
            type: String,
        },
        posts: [{ type: Schema.Types.ObjectId, ref: 'Posts' }],
    },
    { timestamps: true },
);

userSchema.pre('save', function(next) {
    User.findOne({ email: this.email }, (err, user) => {
        if (user) {
            next(new Error('Email already exist in db!'));
        } else {
            next();
        }
    });
});

userSchema.pre('save', function(next) {
    User.findOne({ username: this.username }, (err, user) => {
        if (user) {
            next(new Error('Username exist in db'));
        } else {
            next();
        }
    });
});

const User = mongoose.model('user', userSchema);
module.exports = User;

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new mongoose.Schema(
    {
     _id: mongoose.Schema.Types.ObjectId,
     author: { type: Schema.Types.ObjectId, ref: 'User' },
     title: {
         type: String,
            required: true,
        },
        body: {
            type: String,
            required: true,
        },
        tags: {
            type: [String],
        },
        likes: {
            type: Number,
            default: 0,
        },
    },
    { timestamps: true },
);

const Post = mongoose.model('post', postSchema);
module.exports = Post;

router.post(
    '/posts',
    passport.authenticate('jwt', {
        session: false,
    }),
    postValidationMiddleware,
    (req, res) => {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.status(422).json({ errors: errors.array() });
        }
        User.findOne({ email: req.body.email }).then(author => {
            const post = new Post({
                _id: mongoose.Types.ObjectId(),
                author: author._id,
                title: req.body.title,
                body: req.body.body,
                tags: req.body.tags,
            });
            post.save((err, post) => {
                const posts = author.posts.push(post._id);
                author.save(posts);
            });
        });
        res.status(200).json({ data: 'Post saved' });
    },
);

错误消息:

  

UnhandledPromiseRejection警告:错误:数据库中已经存在电子邮件!

0 个答案:

没有答案