0

I have this code

exports.index = function (req, res) {
res.render('product/index.jade', {
    products: db.products.find().toArray(function (err, prods) {
        if (!err)
            return prods;
        return [];
    })
});

};

What I'm trying to do here is pass the query result to a jade view which expects a parameter named "products". I ve tried a lot of combinations but neither of them works (right now i'm getting "cannot read proprty lenght...."). I know it must be a rookie mistake, but i cannot figure it out, any help will be apreciated!

PS: I'm using express and mongodb. And yes, the products collection does contain products.

4

1 回答 1

1

toArray 实际上并不返回值。相反,一旦查找完成,回调函数就会被调用,并将产品作为参数。这是由于节点的异步 I/O 特性。

您的代码应该看起来像这样

exports.index = function (req, res) {
    db.products.find().toArray(function (err, prods) {
        if (!err)
            res.render('product/index.jade', {products: prods});
        else
            res.render('product/index.jade', {products: []});
    });
});
于 2013-04-15T21:56:10.097 回答