Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在sails.js中从多个集合中获取记录_Node.js_Mongodb_Sails.js_Mongodb Query_Sails Mongo - Fatal编程技术网

Node.js 如何在sails.js中从多个集合中获取记录

Node.js 如何在sails.js中从多个集合中获取记录,node.js,mongodb,sails.js,mongodb-query,sails-mongo,Node.js,Mongodb,Sails.js,Mongodb Query,Sails Mongo,我是sails.js的新手,我正在尝试创建crud并使用sails js登录。我想从多个集合中获取loggedin用户的记录,比如用户配置文件详细信息和登录用户完成的post。 我不知道如何从多个集合中查询,如用户、仪表板(包括用户登录后发布的所有帖子)。如果有人有想法,请与我分享或指导我如何完成这项任务 这是我的仪表板控制器 require('../models/Dashboard.js'); var User = require('../models/User.js'); module.ex

我是sails.js的新手,我正在尝试创建crud并使用sails js登录。我想从多个集合中获取loggedin用户的记录,比如用户配置文件详细信息和登录用户完成的post。 我不知道如何从多个集合中查询,如用户、仪表板(包括用户登录后发布的所有帖子)。如果有人有想法,请与我分享或指导我如何完成这项任务

这是我的仪表板控制器

require('../models/Dashboard.js');
var User = require('../models/User.js');
module.exports = {
     //View all record posted by login user from dashboard collection
    index: function(req, res ){
        //console.log(req.session.passport.user);
        var userId = req.session.passport.user;



    // here i want to get data from user collection and want to send to the view




        Dashboard.find({posted_by: {$in: [userId]}}).exec(function(err, result){
            if(err){
                sails.log("----Error----"+err);
            }else{
            /*  console.log(result);*/
                res.view('dashboard/index',{'result': result}); 
            }
        });
    },
    create: function(req, res){
        //view for new post entry
    //  var userId = req.session.user_detail._id;
    //  sails.log(req.session);
        res.view('dashboard/create');
    },
    newpost: function(req, res){
        // Post New record to dashboard collection
        var params = req.params.all();
        var userId = req.session.passport.user;

        Dashboard.create({ title: params.heading, description: params.message, posted_by: userId }).exec(function(error, post_created){
            if(error){

            }else{
                req.session.post_details = post_created;
                res.redirect('/dashboard');
            }
        });
    },
    removePost: function(req, res)
    {
        // remove record from collection
        var id = req.query.id;
        //var id = req.param("id", null);
        //console.log(id);
        //sails.log(id);
        Dashboard.findOne(id).exec(function(err, user) {
            user.destroy(function(err) {
            res.redirect( 'dashboard/index/');
                  // record has been removed
            });
        });
    },
    update: function(req, res){
        // Get dashboard collection record to update
        var id =req.query.id;
        console.log(id);
        Dashboard.findOne(id).exec( function(err, post){
        //  console.log(post);
        res.view('dashboard/update',{'post':post});
        });
    },
    edit: function (req, res) {
    // Update the record in dashboard collection
    var id = req.param("id",null);
   // var params = req.params.all()
    Dashboard.findOne(id).exec(function(err, dashboard) {
        dashboard.title = req.body.title;
        dashboard.description = req.body.description;
        //user.name = params;
        dashboard.save(function(err){
        if(err) {
            res.send("Error");
        }else {
           res.redirect('dashboard/index');
        }
      });
  });
  },
  profile: function(req, res){
        //view for new post entry
    //  var userId = req.session.user_detail._id;
    //  sails.log(req.session);
        res.view('dashboard/profile');
    },

 /* upload: function(req, res){
    if(req.method === 'GET')
        return res.json({ 'status':'Get Not Allowed'});
    console.log('status: Get Not Allowed');
    var userPhoto =req.file('userPhoto');
    console.log("*******User Photo***********");
    console.log(userPhoto);
    console.log('****************************');
    userPhoto.upload( function onUploadComplete (err, files){
        //file upload to /tmp/public folder

        if(err) return res.serverError(err);
        // if error return  and send 500 error with error
        console.log("*************** Uploaded file ************* ");
        console.log(files);
        var id = req.session.passport.user;
        //res.json({status: 200, file: files});
        User.findOne(id).exec( function (err, user){
            user.userName = req.body.userName;
            user.userPhoto = req.body.files;
            user.save(function (err){
                if(err) { console.log("Error updating profile");}
                res.redirect('dashboard/index');
            });

        });
    });
  }*/
};
这是我的用户模型

  var bcrypt = require('bcrypt');

module.exports = {
    attributes: {
        username:{
            type: 'string'
        },
        userphoto: {
            type: 'string'            
        },
        email: {
            type: 'email',
            required: true,
            unique: true
        },
        password: {
            type: 'string',
            minLength: 6,
            required: true
        },
        toJSON: function() {
            var obj = this.toObject();
            delete obj.password;
            return obj;
        }
    },
    beforeCreate: function(user, cb) {
        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(user.password, salt, function(err, hash) {
                if (err) {
                    console.log(err);
                    cb(err);
                } else {
                    user.password = hash;
                    cb();
                }
            });
        });
    }
};
这是我的仪表板模型

module.exports = {

  attributes: {
    title:{
         type:'string',
         //required:true,
         columnName:'title'
    },
    description: {
         type:'text',
         columnName:'description'
    },
    posted_by: {
        type: 'integer',
        columnName: 'posted_by'
    }

  }
};

提前感谢

您可以像这样嵌套查询:

index: function(req, res ){
    var userId = req.session.passport.user;

    // here i want to get data from user collection and want to send to the view
    User.findOne({id: userId}).exec(function(err, user) { // `id` might be `$id` in mongodb?
        Dashboard.find({posted_by: {$in: [userId]}}).exec(function(err, result) {
            if(err){
                sails.log("----Error----"+err);
            }else{
                res.view('dashboard/index',{'result': result, 'user': user}); 
            }
        });
    })
}
正如注释所述,mongoDB可能有
$id
而不是
id
,因此如果这不起作用,请尝试一下

另一种防止回调地狱问题的方法是使用,其工作原理如下:

var Promise = require('bluebird');

...


index: function(req, res ){
    var userId = req.session.passport.user;

    // here i want to get data from user collection and want to send to the view
    Promise.all([
        User.findOne({id: userId}),
        Dashboard.find({posted_by: {$in: [userId]}})
    ])
    .spread(function(user, result) {
        return res.view('dashboard/index',{'result': result, 'user': user}); 
    })
    .catch(function(err) {
        return res.serverError({status: 500, message: 'Something went wrong :('})
    })
}

可以按如下方式嵌套查询:

index: function(req, res ){
    var userId = req.session.passport.user;

    // here i want to get data from user collection and want to send to the view
    User.findOne({id: userId}).exec(function(err, user) { // `id` might be `$id` in mongodb?
        Dashboard.find({posted_by: {$in: [userId]}}).exec(function(err, result) {
            if(err){
                sails.log("----Error----"+err);
            }else{
                res.view('dashboard/index',{'result': result, 'user': user}); 
            }
        });
    })
}
正如注释所述,mongoDB可能有
$id
而不是
id
,因此如果这不起作用,请尝试一下

另一种防止回调地狱问题的方法是使用,其工作原理如下:

var Promise = require('bluebird');

...


index: function(req, res ){
    var userId = req.session.passport.user;

    // here i want to get data from user collection and want to send to the view
    Promise.all([
        User.findOne({id: userId}),
        Dashboard.find({posted_by: {$in: [userId]}})
    ])
    .spread(function(user, result) {
        return res.view('dashboard/index',{'result': result, 'user': user}); 
    })
    .catch(function(err) {
        return res.serverError({status: 500, message: 'Something went wrong :('})
    })
}

由属性发布的
是否为用户id?如果是,您应该使用

// In the Dashboard model
module.exports = {

  attributes: {
    // ...
    posted_by: {
      model:'User'
    }
  }

}
User.findOne({id: userId}).populate('dashboards').exec(function(err, user) {
  // Here, user.dashboards is populated
  res.view('dashboard/index',{'user': user}); 
})
在用户模型中也定义关系:

// In the User model
module.exports = {

  attributes: {
    // ...
    dashboards: {
      collection: 'Dashboard',
      via: 'posted_by'
    }
  }

}
定义了关系后,仪表板将显示在用户模型中

如果您不想使用蓝图,可以使用

// In the Dashboard model
module.exports = {

  attributes: {
    // ...
    posted_by: {
      model:'User'
    }
  }

}
User.findOne({id: userId}).populate('dashboards').exec(function(err, user) {
  // Here, user.dashboards is populated
  res.view('dashboard/index',{'user': user}); 
})
我也会将
发布的
重命名为
用户
,但这是一个品味问题


如果您的模型没有关联或有更深层的关联,Fissio的答案非常有用。

发布的
属性是用户id吗?如果是,您应该使用

// In the Dashboard model
module.exports = {

  attributes: {
    // ...
    posted_by: {
      model:'User'
    }
  }

}
User.findOne({id: userId}).populate('dashboards').exec(function(err, user) {
  // Here, user.dashboards is populated
  res.view('dashboard/index',{'user': user}); 
})
在用户模型中也定义关系:

// In the User model
module.exports = {

  attributes: {
    // ...
    dashboards: {
      collection: 'Dashboard',
      via: 'posted_by'
    }
  }

}
定义了关系后,仪表板将显示在用户模型中

如果您不想使用蓝图,可以使用

// In the Dashboard model
module.exports = {

  attributes: {
    // ...
    posted_by: {
      model:'User'
    }
  }

}
User.findOne({id: userId}).populate('dashboards').exec(function(err, user) {
  // Here, user.dashboards is populated
  res.view('dashboard/index',{'user': user}); 
})
我也会将
发布的
重命名为
用户
,但这是一个品味问题


如果您的模型没有关联或有更深层的关联,Fissio的答案非常有效。

水线已经提供了,但不是
。所有的
都比使用
的承诺链更有效。那么
?我知道它可以同时对两个承诺起作用,因为它们互不依赖。水线已经提供了,它不是
。所有的
仍然比使用
的承诺链更有效。那么
?我明白,它可以同时实现两个承诺,因为它们互不依赖