我想在mongoose中生成带函数的字段。因为有很多字段,但它们大同小异,所以我想使用函数来创建它们,以保持代码简短。
我写了一个函数,但确实存在lints。
import { Schema } from 'mongoose'
function fieldGen(name, type="string", isRequired=true) {
var field = {}
field[name] = {
type: type,
required: isRequired
}
return {...field}
}
const testSchema = new Schema({
fieldGen("firstname")
fieldGen("lastname")
fieldGen("location")
})
在VS代码中,问题显示如下
Identifier expected. ts(1003) [20, 12]
我期望第一个参数"firstname“与函数中的name匹配,并返回object。
发布于 2019-08-14 00:59:10
您正在向testSchema
对象添加值,而没有为它们指定名称。
另外,您将把field
对象的属性扩展到一个新的对象文字中。这并不能完成任何事情。仅仅返回field
对象也会产生相同的结果。
我明白你想做什么了。如果您以较小的步骤对此进行调试,并仔细查看您正在处理的数据,我认为您将自己解决问题。
https://stackoverflow.com/questions/57486809
复制