首页 > 解决方案 > 如何将输入字段映射为mongodb中的不同字段

问题描述

假设我在 MongoDB 中插入数据为

db.collection.insertMany([{username:'Jack',msg:'hello'},{username:'Jenny',msg:'hello world'},{username:'Rose',msg:'Hi howz You'}])

现在我希望这样插入这些数据:

{account_username:'Jack',msg:'hello'}
{account_username:'Jenny',msg:'hello world'}
{account_username:'Rose',msg:'Hi howz You'}

而不是这个:

{username:'Jack',msg:'hello'}
{username:'Jenny',msg:'hello world'}
{username:'Rose',msg:'Hi howz You'}

我在我的 NodeJS 代码中使用 mongoose,我可以在 Schema 中做些什么,所以只要输入是用户名,它就会自动引用我定义的 mongoose Schema 的 account_username。

标签: node.jsmongodbmongoosemongodb-querymongoose-schema

解决方案


如果将 mongoose 与 mongoDB 一起使用,则可以使用 mongoose 虚拟功能功能轻松做到这一点,Mongoose Virtuals

Mongoose Viruals 具有 Setter 和 Getter,它们具有定义具有不同名称的列的功能


推荐阅读