创建和更新todayworker状态,无重复

时间:2014-09-23 06:48:52

标签: node.js mongodb mongoose

this is my document in worker collection i want when I delete the id. today worker change to 2. 

我将再次添加相同的ID今天工作人员更改为0.但同样的ID不再创建我只需要更改今天的工作状态?

输出:   “_id”:ObjectId(“542012b5b79597180574255d”),       “userId”:ObjectId(“54052de21b7a0d0b00739cf9”),       “createdDate”:ISODate(“2014-09-22T12:14:45.78Z”),       “todayWorker”:2,

我使用下面的代码,但没有正常工作,请给我一个解决方案任何人

workerschema code
var workerSchema = new mongoose.Schema({
userId:{type:Schema.Types.ObjectId, ref: 'User'},
todayWorker:{type:Number,default:0,enum:[0,1,2]}, 
createdDate:{type: Date,default:Date.now }

});

  //delete worker code(while delete properly changed todatworker status) 
var options1={multi:true};
        //Worker.remove(selection,function(err,status){
            Worker.update(selection,{$set:{todayWorker:2}},options1,function(err,status){
            if(err)
                res.send(err);
            else
            {
                res.json({"success":true,"message":"Workers Deleted"});
            }
        });
//add worker code (but insert time not changed todayworker status)
var idObjects=createObjectIds(idsarray);        
    var selection={_id:{$in:idObjects}};
    //console.log(selection);
    if(todayWorker==0){
        var projection={_id:1};
        var callback1=function(err,users){
            if(err)
                res.send(err);
            else{
                var count1=users.length;                
                for(var i=0;i<count1;i++){
                    Worker.findOneOrCreate({userId:users[i].id},{userId:users[i].id,todayWorker:todayWorker},function(err,worker){
                        //Worker.findAndModify({query:{userId:users[i].id},update{$setOnInsert:{todayWorker:"todayWorker"}}},{ upsert: true },function(err,Worker){
                            //Worker.update({userId:users[i].id},{$setOnInsert:{ userId:users[i].id,todayWorker:todayWorker,createdDate:Date.now()}},{ upsert: true },function(err,Worker){
                        if(err)
                            res.send(err);
                        else
                        {

                            count2++;
                            if(count2==count1)

                                res.json({"status":true,"message":"Worker Added"});
                        }
                    });
                }
            }
        }
        User.find(selection,projection,callback1);
}
else
{
    res.send("No user found");
}

};

0 个答案:

没有答案