如何修改Mongoose查询中返回的数据?

时间:2015-08-21 06:07:51

标签: javascript node.js mongodb mongoose nosql

我已经调用了lean()来确保我已将返回的数据转换为普通对象,但只有故事[x] .authorId没有被添加为当前故事的属性[ x]对象。

有人可以解释原因并提供解决方案吗?它是否与范围有关,还是我不能在另一个查询中修改对象?

Story.find({}).sort({created: -1}).lean().exec(function(err, stories) {
    if (err) throw err;
    for(var x=0; x < stories.length; x++) {
        stories[x].commentsLength = stories[x].comments.length; 
        stories[x].created = stories[x]._id.getTimestamp();
        stories[x].timeAgo = timeHandler(stories[x]);
        User.find({'username': stories[x].author}).lean().exec(function(x, err, data) {
            stories[x].authorId = data[0]._id;
                console.log(stories[x]); // authorId is there
        }.bind(this, x));
        console.log(stories[x]); // authorId is not there
    }
    res.render('news', {message: "Homepage", data: stories});
})

1 个答案:

答案 0 :(得分:0)

我认为您在调用异步stories[x]函数后尝试注销User.find()。由于User.find()以异步方式运行,因此在调用完成之前,您将无法访问其结果。换句话说,这是预期的行为。

还有一点需要注意的是,如果您使用.forEach模块中的async.each甚至Story.find({}).sort({created: -1}).lean().exec(function(err, stories) { if (err) throw err; stories.forEach(function(story) { story.commentsLength = story.comments.length; story.created = story._id.getTimestamp(); story.timeAgo = timeHandler(story); User.find({ 'username': story.author }).lean().exec(function(x, err, data) { story.authorId = data[0]._id; console.log(story); // authorId is there, because this means User.find completed }.bind(this, x)); console.log(story); // authorId is not there, and never will be, because this function executes before User.find completes its lookup }); res.render('news', { message: "Homepage", data: stories }); }); 等迭代器函数,您可能会发现代码更容易阅读:

function getStory(callback) {
    Story.find({}).sort({created: -1}).lean().exec(function(err, stories) {
        if (err) throw err;
        async.each(stories, function(story, callback) {
            story.commentsLength = story.comments.length;
            story.created = story._id.getTimestamp();
            story.timeAgo = timeHandler(story);
            User.find({
                'username': story.author
            }).lean().exec(function(x, err, data) {
                story.authorId = data[0]._id;
                callback(err, story);
            }.bind(this, x));
        }, function(err, results) {
            callback(err, results); // results is now an array of modified stories
        });
        res.render('news', {
            message: "Homepage",
            data: stories
        });
    })
}

如果您尝试修改返回数据,可以使用async确保在执行回调之前完成所有查找功能:

>>> root = Tkinter.Tk()
>>> Tkinter.Entry(root)
>>> root.winfo_children()
[(Tkinter.Entry instance at _____)]
相关问题