【问题标题】:Node Mongoose virtual property return children matching criteria节点 Mongoose 虚拟属性返回子匹配条件
【发布时间】:2018-01-24 19:03:23
【问题描述】:

在 Mongoose 应用程序中,我可以使用虚函数通过 ref 查找子对象。

我的问题是,给定一个父对象,它与许多具有两个日期(start_date、end_date)的子对象有 ref 关系。

父对象:

{
    "id": 12345,
    "children": [...] // <= A virtual property to the child objects below.
}

子对象

[{
    "parent": 12345,
    "start_date": "2016-01-01",
    "end_date":   "2016-02-01"
},
{
    "parent": 12345,
    "start_date": "2016-02-02",
    "end_date":   "2016-03-01"
}]

理想情况下,我希望有一个名为 current 的虚拟属性,它返回当前日期介于 start_date 和 end_date 之间的子对象。

例如,如果今天是“2016-02-20”,我希望结果如下所示:

{
    "id": 12345,
    "children": [...], // <= A virtual property to the child objects below.
    "current": {
        "parent": 12345,
        "start_date": "2016-02-02",
        "end_date":   "2016-03-01"
    }
}

我尝试在虚函数中查找子属性,但似乎由于它是一个promise,它总是返回null。我不确定是否有更简单的方法来做到这一点,但我真的很感激任何想法。

这是我尝试过的,但总是返回 null。即使我登录到控制台并且结果显示在那里:

ParentSchema
.virtual('current')
.get(function () {
   var result = null;
   ChildModel.find({parent: this._id}, function (err, results) {
       // ... some logic here to find the correct item. (Omitted for brevity).
       result = foundItem;
   });
   return result;
})

非常感谢!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    记住 mongoose 操作是异步的,所以你需要等待它们的回调被调用才能得到结果。

    ParentSchema.virtual('current').get(function () {
        var result = null;
        ChildModel.find({parent: this._id}, function callback(err, children) {
            // ...
            result = child;
        });
        // by the time it reaches this point, the async function ^ will not yet be finished -- so result will always be null
        return result; 
    })
    

    (1) 要使用虚拟属性,您必须返回 Promise 而不是值。

    ParentSchema.virtual('current').get(function () {
        var self = this;
        return ChildModel.find({ parent: self._id }, function (err, children) {
            // ...
            self.current = child;
        });
    })
    

    你会像这样使用它

    parent.current.then(function () {
        console.log(parent.current);
    }).catch(function (err) {
        // ...
    })
    

    (2) 我认为最好还是使用方法。

    ParentSchema.methods.getCurrent(function (callback) {
        var self = this;
        ChildModel.find({ parent: self._id }, function (err, children) {
            if (err) return callback(err);
            // ...
            self.current = child;
            callback();
        });
    });
    

    你会像这样使用它

    parent.getCurrent(function (err) {
        console.log(parent.current);
    })
    

    【讨论】:

    • 优秀的概述。非常感谢!
    猜你喜欢
    • 2021-02-07
    • 2019-06-17
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多