如何从sails.js

时间:2015-08-18 10:50:13

标签: node.js mongodb sails.js mongodb-query sails-mongo

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

这是我的Dashboardcontroller

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');
            });

        });
    });
  }*/
};

这是我的Usermodel

  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'
    }

  }
};

提前致谢

2 个答案:

答案 0 :(得分:3)

posted_by属性是否为用户ID?如果是,您应该使用OneToMany relation

// In the Dashboard model
module.exports = {

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

}

在用户模型中定义关系:

// In the User model
module.exports = {

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

}

定义关系后, Dashboards 将显示在{{3>} 用户模型中。

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

User.findOne({id: userId}).populate('dashboards').exec(function(err, user) {
  // Here, user.dashboards is populated
  res.view('dashboard/index',{'user': user}); 
})

我也会将posted_by重命名为user,但这是一个品味问题!

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

答案 1 :(得分:1)

您可以像这样嵌套查询:

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,所以如果这不起作用,请尝试使用。

另一种方法 - 我更喜欢阻止回调地狱问题 - 是使用Bluebird,它可以如下工作:

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 :('})
    })
}