“IProtein”类型上不存在属性“save”。ts(2339)

问题描述 投票:0回答:1

我正在尝试使用猫鼬“保存”功能,但此错误显示(“类型‘IProtein’.ts(2339) 上不存在属性‘保存’”)。

我看到你可以通过在接口中添加“extends mongoose.Document”来解决这个问题,但在文档中不建议这样做,我怎样才能正确解决这个问题?

谢谢!

import * as mongoose from "mongoose";

interface IProtein  {
    seller: mongoose.Schema.Types.ObjectId;
    name: string;
    description: string;
    price: Number;
    flavour: string;
}

const proteinSchema = new mongoose.Schema<IProtein>({
    seller: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    name: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    flavour: {
        type: String,
        required: true
    }
})

const Protein: mongoose.Model<IProtein> = mongoose.model('Protein', proteinSchema);
export { Protein, IProtein };
export const updateProtein = asyncHandler(async (req: any, res: any) => {
    const currentName: string = req.params.name
    const { name, description, price, flavour } : 
        { name: string | null, description: string | null, price: number | null, flavour: string | null } = req.body

    if (!name && !description && !price && !flavour) {
        return res.status(400).json({ message: 'No field got changed' })
    }

    const protein: Protein.IProtein | null = await Protein.Protein.findOne({ currentName }).lean().exec()

    if (!protein) {
        return res.status(400).json({ message: 'Protein not found' })
    }

    const duplicate: Protein.IProtein[] | null = await Protein.Protein.find({ currentName }).lean().exec()

    if (duplicate.length > 1) {
        return res.status(409).json({ message: 'Duplicate protein title' })
    }

    if (protein)
    {
        if (name)
            protein.name = name
        if (description)
            protein.description = description
        if (price)
            protein.price = price
        if (flavour)
            protein.flavour = flavour

        const updatedProtein = await protein.save() //This is the problem

        res.json(`'${updatedProtein.name}' updated`)
    }
})
node.js typescript mongodb express mongoose
1个回答
2
投票

我通过从猫鼬库扩展文档解决了同样的问题。 这样,对象就可以有“保存”方法了。

import mongoose, { Schema, Types, Document } from "mongoose";

interface IProtein extends Document {
seller: mongoose.Schema.Types.ObjectId;
name: string;
description: string;
price: Number;
flavour: string;
}
© www.soinside.com 2019 - 2024. All rights reserved.