首页 > 解决方案 > 当我使用地理编码器时,我的中间件不起作用

问题描述

我尝试使用发布请求创建用户。

我制作了一个中间件来加密用户密码。在此之前,一切正常,我可以在 postman 上创建我的用户。

餐厅模型

restaurantSchema.pre("save", async function (next) {
    const salt = await bcrypt.genSalt();

    this.password = await bcrypt.hash(this.password, salt);

    next();
});

但是,我想将地理编码器添加到我的中间件中,只是为了将我的用户地址转换为坐标。但是当我这样做时,我的中间件不起作用。我的控制台上没有任何消息,我只去捕获我的“addRestaurant”函数。

餐厅模型

restaurantSchema.pre("save", async function (next) {
const salt = await bcrypt.genSalt();

const loc = await geocoder.geocode(this.address);
console.log("geo");

this.password = await bcrypt.hash(this.password, salt);

this.location = {
    type: "Point",
    coordinates: [loc[0].longitude, loc[0].latitude],
    formattedAdress: loc[0].formattedAdress,
};

next();

});

餐厅模式

const restaurantSchema = new mongoose.Schema(
{
    identifiant: {
        type: String,
        required: true,
        minLength: 3,
        maxLenght: 55,
        unique: true,
        trimp: true,
    },
    name: {
        type: String,
        required: true,
        minLength: 3,
        maxLenght: 55,
        unique: true,
        trimp: true,
    },
    email: {
        type: String,
        required: true,
        validate: [isEmail],
        lowercase: true,
        unique: true,
        trim: true,
    },
    password: {
        type: String,
        required: true,
        max: 1024,
        minlength: 6,
    },
    telephone: {
        type: String,
        max: 30,
    },
    horaire: {
        type: String,
        default: "non renseigné",
    },
    address: {
        type: String,
        required: true,
    },
    reseaux: {
        type: String,
    },
    picture: {
        type: String,
        default: "./upload/profil/random-user.png",
    },
    location: {
        type: {
            type: String,
            enum: ["Point"],
        },
        coordinates: {
            type: [Number],
            index: "2dspher",
        },
        formattedAdress: String,
    },
    createdAt: {
        type: Date,
        default: Date.now,
    },
},
{
    timestamps: true,
}

);

**认证控制器**

module.exports.signUp = async (req, res) => {
    const { identifiant, name, email, password, address } = req.body;

    try {
        const restaurant = await RestaurantModel.create({
            identifiant,
            name,
            email,
            password,
            address,
        });
        res.status(201).json({
            restaurant: restaurant._id,
            success: true,
            data: restaurant,
        });
    } catch (err) {
        const errors = signUpErrors(err);
        res.status(200).send({ errors });
    }
};

我真的不知道为什么..

标签: node.jsmongoosegeocodingmongoose-schemamapquest

解决方案


推荐阅读