javascript - NodeJS 和 MongoDB - ObjectId 数组如何返回对象

标签 javascript json node.js mongodb

我在一个集合中有一个 ObjectId 的引用数组。我想返回与 json 响应中的这些 Id 链接的对象数据。

retrieveFromUser: function( req, res ) {
    var user_id =   req.params.user_id;
    User.findById( user_id, function( err, user ) {
        if( err ) {
            res.send( 404, "Unable to find user");
        } else {
            // This returns the array but I want the objects data
            return res.json( user.constructions );
        }
    });
}

我该怎么做?
非常感谢!

最佳答案

尝试使用populate()方法

retrieveFromUser: function( req, res ) {
 var user_id =   req.params.user_id;
    User.findOne({ _id: user_id }).populate('constructions').exec(function( err, user ) {
        if( err ) {
            res.send( 404, "Unable to find user");
        } else {
            // This returns the array but I want the objects data
            return res.json( user.constructions );
        }
    });
}

关于javascript - NodeJS 和 MongoDB - ObjectId 数组如何返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19290585/

相关文章:

javascript - React Router 路径渲染多个组件

javascript - onmouseover 在 onmousemove 触发

javascript - NodeJS 同步调用

Javascript - 如何从 JSON 数组 (URL) 创建变量?

jquery - 为什么jquery将json作为参数名称而不是作为请求正文发布?

javascript - Express Generator app.use ('/login',用户)不拾取路线

node.js - 如何使用任何库调用 FIXAPI(nodejs 的 fixparser)?

javascript - 更改禁用按钮的颜色

java - Jersey json web 服务客户端实现

node.js - 是否可以同步进行 Gradle 调用?