My JSON response contains a field first_name but I want my Mongoose model to represent this field as firstName. Is this possible and if so then how?
我的JSON响应包含字段first_name但我希望我的Mongoose模型将此字段表示为firstName。这是可能的,如果是这样,那怎么样?
1 个解决方案
#1
0
You can create a new object with different property names from the one Mongoose returns. A nice way of doing this is by creating a function that uses object deconstruction. For example, let's say this is your schema:
您可以使用一个Mongoose返回的不同属性名创建一个新对象。这样做的一个好方法是创建一个使用对象解构的函数。例如,假设这是您的架构:
{
firstName: { type: String, required: true },
lastName: { type: String, required: true }
}
Then you can use this function to create a new object with the desired property names:
然后,您可以使用此函数创建具有所需属性名称的新对象:
const filterDocument = ({ firstName, lastName }) => ({
first_name: firstName,
last_name: lastName
})
Then, when you query the DB, you apply this function to the response:
然后,当您查询数据库时,将此函数应用于响应:
Person.findOne({ firstName: 'John', lastName: 'Smith' })
.then(filterDocument)
#1
0
You can create a new object with different property names from the one Mongoose returns. A nice way of doing this is by creating a function that uses object deconstruction. For example, let's say this is your schema:
您可以使用一个Mongoose返回的不同属性名创建一个新对象。这样做的一个好方法是创建一个使用对象解构的函数。例如,假设这是您的架构:
{
firstName: { type: String, required: true },
lastName: { type: String, required: true }
}
Then you can use this function to create a new object with the desired property names:
然后,您可以使用此函数创建具有所需属性名称的新对象:
const filterDocument = ({ firstName, lastName }) => ({
first_name: firstName,
last_name: lastName
})
Then, when you query the DB, you apply this function to the response:
然后,当您查询数据库时,将此函数应用于响应:
Person.findOne({ firstName: 'John', lastName: 'Smith' })
.then(filterDocument)