【发布时间】:2016-04-17 00:52:56
【问题描述】:
我有以下架构:
var TestSchema = db.Schema({
name: { type: String, required: true, unique: true }
data: []
},
{ strict: false });
var Test = db.model('Test', TestSchema);
注意它是strict: false。我希望能够upsert 新文件。问题是,我不希望 data 数组被覆盖,而是希望将新文档推入其中。
例如,假设这是一个现有文档:
{ name: "hello world",
data:
[ { one: '123',
two: '456' } ]
}
我想upsert这个:
{ name: "hello world",
new_field: "to be updated"
data:
[ { one: 'pushed to the array',
two: 'xyz' } ]
}
预期的结果是:
{ name: "hello world",
new_field: "to be updated"
data:
[ { one: 'abc',
two: 'xyz' },
{ one: 'pushed to the array',
two: 'xyz'} ]
}
明确说明:文档已经存在,所以应该更新。新字段 new_field 已更新。但是,我们不会覆盖现有的 data 数组(如常规更新那样),而是将新文档推送到数组中。
我有一个非常丑陋的工作版本,它使用三个调用来实现这一点,这是完全不可用的(异步 -> 当您同时抛出许多查询时,重复插入而不是更新)。
这真的可以在 Mongoose 中实现吗?
【问题讨论】:
标签: javascript node.js mongodb mongoose mean-stack