【发布时间】:2020-07-09 17:51:52
【问题描述】:
我正在尝试在 MongoDB 集合中更新或创建文档,以这种方式使用“mongoose”:
this.statsModel.findOne(
{product_id: requestData.ean},
).then((stats: mongoose.Schema) => {
const productId: string = requestData.ean;
// Update stats with the new scan...
const beforeStats: mongoose.Schema = stats;
const scan: any = {
coords: {
lat: requestData.lat,
lon: requestData.lon,
},
at: new Date(),
};
if (stats) {
stats.scans.push(scan);
stats.update();
} else {
const newStat = new this.statsModel();
newStat._id = requestData.ean;
newStat.product_id = requestData.ean;
newStat.scans = [scan];
newStat.purchases = [];
newStat.save();
}
当此代码运行时,如果有统计文档,则“扫描”属性中不会出现新元素。
如果未找到 stats 文档,则正确创建文档。
我尝试将“update()”方法更改为“save()”方法,但是,这样,我得到一个“版本错误没有匹配的文档为 id...”
我做错了什么?
问候...
【问题讨论】:
-
已经检查过了,但没有回答这个问题......在我的例子中,“stats”已经是一个 Mongo 文档,所以,根据文档,我可以保存它而不是必须先创建另一个文档。