获取更新文档的ObjectID

时间:2016-08-17 22:52:05

标签: mongodb node-mongodb-native

我尝试使用upsert更新父文档中包含所有子文档ID的父文档。问题是只有在upsert导致插入发生时才会返回ID。

我已经获得了以下代码,这些代码在插入新孩子时有效但是一旦更新了诺言,由于结果被提升为null,诺言会锁定。

        let promises = [];
        parent.children.forEach(child => {
            //Child contains everything except the _id
            promises.push(database.collection('Children').updateOne(
                child,
                child,
                {
                    upsert: true
                }
            ));
        });

        Promise.all(promises).then(result => {
            delete parent.children;
            parent.childIds = result.map(upsert => new ObjectId(upsert.upsertedId._id)); //ONLY THERE ON INSERT?
            database.collection('Parents').updateOne({
                parentId: obj.parentId
            }, obj, {
                upsert: true
            }).then(() => {
                //some success functionality
            }, error => {
                //some error functionality
            });
        }, error => {
            //some error functionality
        });

1 个答案:

答案 0 :(得分:1)

似乎解决方案是使用findOneAndUpdate方法。此方法将找到一个对象,更新它然后返回该文档。它还接受upsert参数,因此在未找到特定文档时执行插入。

如果执行更新,结果将包含value字段下的文档。

如果执行了插入(当upsert为true时),将在结果对象中设置字段lastErrorObject.upsertedvalue字段将为null

以下是修复我的问题的代码:

        let promises = [];
        parent.children.forEach(child => {
            promises.push(database.collection('Children').findOneAndUpdate(
                child,
                child,
                {
                    upsert: true
                }
            ));
        });

        Promise.all(promises).then(result => {
            delete parent.children;
            parent.childrenIds = result.map(upsert => new ObjectID(upsert.lastErrorObject.upserted || upsert.value._id));
            database.collection('Parents').updateOne({
                parentId: parent.parentId
            }, obj, {
                upsert: true
            }).then(() => {
                //some success functionality
            }, error => {
                //some error functionality
            });
        }, error => {
            //some error functionality
        });