mongoose如何给每个item加一个字段?

比如

[
{a:1,b:2},
{a:2,b:44}
]

现在我要加一个字段c,
变成

[
{a:1,b:2,c:33},
{a:2,b:44,c:666}
]

怎么弄?

阅读 2.2k
1 个回答

mongoose 是mongodb 的一个对象模型。讲究 schame, model, document 三种对象,定义的schema 其实就是mongodb中的结构

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

每个schema 就是映射了mongodb 的集合, 看这里

If you want to add additional keys later, use the Schema#add method.

来看看:

const ToySchema = new Schema();
ToySchema.add({ name: 'string', color: 'string', price: 'number' });

const TurboManSchema = new Schema();
// You can also `add()` another schema and copy over all paths, virtuals,
// getters, setters, indexes, methods, and statics.
TurboManSchema.add(ToySchema).add({ year: Number });

Schema#add

上面这种是使用方法去在已经定义好的上面增加

在我实践过程中,其实直接修改schema 结构,在代码运行后会直接反馈在集合结构中,也就是说会和当前集合自动合并。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题