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



我正在尝试使用猫鼬"保存";函数,但此错误显示("类型‘IProtein’.ts(2339(上不存在属性‘save’"(。

我看到你可以通过添加";扩展了猫鼬。文件";到接口,但在文档中不建议这样做,我如何正确解决这个问题?

谢谢!

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`)
}
})

我通过从mongoose库扩展Document解决了同样的问题。通过这种方式,对象可以具有"save"方法。

import mongoose, { Schema, Types, Document } from "mongoose";
interface IProtein extends Document {
seller: mongoose.Schema.Types.ObjectId;
name: string;
description: string;
price: Number;
flavour: string;

}

最新更新