mongodb 推送到集合中的数组后无法保存数据

gjmwrych  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(187)

mongoose函数.保存()不起作用。

async function insertContainerizedData(data, id, farmerId) {
    console.log('test id: ', new ObjectId(id));
    const user = await Storage.findOne({'containerizedBatches.storage_id': new ObjectId(id)});
    console.log('userrrr', user);
    if (user == null) {
        const containerizedBatched = await Storage.updateOne({'farmer_id': farmerId}, {
            $push: {
                containerizedBatches: {
                    storage_id: new ObjectId(data.storage_id),
                    trace_id: data.trace_id,
                    batch_id: data.batch_id,
                    actual_quantity: data.actual_quantity,
                    remaining_quantity: data.remaining_quantity,
                    actual_container: data.actual_container,
                    remaining_container: data.remaining_container,
                    container_type: data.container_type,
                    grade: data.grade
                }
            }
        });
        const result = await containerizedBatched.save(async (err, result) => {
            if (err) {
                throw new Error('item is not saved');
            } else {
                return result;
            }
        });
        console.log('result after push', result);
        return result;

这是我的代码,输出如下所示。我想做的是,如果user == null,我需要将所有数据(req.body)作为对象推入一个数组,数组的名称为containerizedBatches。

"debugMessage": "containerizedBatched.save is not a function",
tcomlyy6

tcomlyy61#

在运行update之后,就不需要再运行save了。containerizedBatchedupdate操作的结果,而不是save的模型。

相关问题