我不确定我是否遇到麻烦,因为我不懂JS或mongodb / mongoose .

这是我目前的代码:

/**
 * Fins all (biological) siblings of this person.
 * @returns {Array} Returns all the siblings as a list. If no siblings were found, returns an empty list.
 */
personSchema.methods.getSiblings = function () {
    const sibs = new Set();

    this.model('Person').findById(this.mother, function(err, mom) {
        mom.children.forEach((child) => { sibs.add(child); });
    });

    this.model('Person').findById(this.father, function(err, pa) {
        pa.children.forEach((child) => { sibs.add(child); });
    });

    console.log(sibs);
    return sibs;
}

我希望这个功能能让这些人的所有孩子都成为父亲和母亲,并将他们的ids作为清单返回(有效地将这些人归还给生物兄弟姐妹) . 现在这个函数唯一能返回的是空集 . 我想我理解为什么,这是因为函数不会在返回之前等待查询完成 . 但是我如何实现这一目标呢?我知道我可以使用promises,但我想添加父亲的孩子,即使母亲查询返回错误...

谢谢您的帮助!

PS:有没有更好的方法将列表的所有元素添加到集合中?

编辑:我找到了解决方案,但它可能不是最佳的:

/**
* Finds all biological siblings of this person.
 * @param callback(sibs) the function to call when finished. Sets the sibs parameter of the callback function to a list
 * of sibling IDs or an empty list if no siblings were found.
 */
personSchema.methods.getSiblings = function (callback) {

const self = this;
const mId = this.mother;
const pId = this.father;
const sibs = [];

self.model('Person').findById(mId, "children", function (err, res) {
    if (!err)
        sibs.push(res.children);

    self.model('Person').findById(pId, "children", function (err, res) {
        if (!err)
            sibs.push(res.children);

        callback(_.uniqWith(sibs, _.isEqual));
    })
});

}