Esempio n. 1
0
app.use("/save",function(req, res){
    var result = {code:0};
    var document = req.query.document;
    var setName = req.query["setName"];
    var callback = req.query["callback"];
    console.log("*******************************************");
    console.log("[callback]:"+callback + " [SAVE TO]:"+setName);
    if(typeof document == "string"){
        document = JSON.parse(document);
    }
    if(!document._id){//---新建的,生成_id;
        var objId = new ObjectID();
        document._id = objId.toHexString();
    }
    console.log(document);
    if(!setName){
        resSendWithCallback(callback, {code:-1,"errmsg":"未指定保存集合的名称"}, res);
        return;
    }
    doMongoDB(function(err,db){
        if(err){
            resSendWithCallback(callback ,(err||{code:-1}),res);
        }
        var collection = db.collection(setName);
        collection.save(document, function(err){
            if(err){
                resSendWithCallback(callback ,err, res);
            }else{
                resSendWithCallback(callback ,{"code":0},res);
            }
            db.close();
        });
    })
});
Esempio n. 2
0
  async updateItem(order_id, item_id, data) {
    if (!ObjectID.isValid(order_id) || !ObjectID.isValid(item_id)) {
      return Promise.reject('Invalid identifier');
    }
    let orderObjectID = new ObjectID(order_id);
    let itemObjectID = new ObjectID(item_id);
    const item = this.getValidDocumentForUpdate(data);

    if(parse.getNumberIfPositive(data.quantity) === 0) {
      // delete item
      return this.deleteItem(order_id, item_id);
    } else {
      // update
      await ProductStockService.handleDeleteOrderItem(order_id, item_id);
      await mongo.db.collection('orders').updateOne({
          _id: orderObjectID,
          'items.id': itemObjectID
        }, {
          $set: item
        });

      await this.calculateAndUpdateItem(order_id, item_id);
      await ProductStockService.handleAddOrderItem(order_id, item_id);
      return OrdersService.getSingleOrder(order_id);
    }
  }
Esempio n. 3
0
	deleteImage(productId, imageId) {
		if (!ObjectID.isValid(productId) || !ObjectID.isValid(imageId)) {
			return Promise.reject('Invalid identifier');
		}
		let productObjectID = new ObjectID(productId);
		let imageObjectID = new ObjectID(imageId);

		return this.getImages(productId)
			.then(images => {
				if (images && images.length > 0) {
					let imageData = images.find(
						i => i.id.toString() === imageId.toString()
					);
					if (imageData) {
						let filename = imageData.filename;
						let filepath = path.resolve(
							settings.productsUploadPath + '/' + productId + '/' + filename
						);
						fse.removeSync(filepath);
						return db
							.collection('products')
							.updateOne(
								{ _id: productObjectID },
								{ $pull: { images: { id: imageObjectID } } }
							);
					} else {
						return true;
					}
				} else {
					return true;
				}
			})
			.then(() => true);
	}
Esempio n. 4
0
	this.getCollection(function(error, book_collection) {
		if (error) callback(error);
		else {
			var updateValue = {};
			if (arrayIndex == -1) {
				if (param == "links") updateValue[param] = [edit.split(',')[0], edit.split(',')[1]];
				else updateValue[param] = edit;
				book_collection.update(
					{_id:ObjectID.createFromHexString(bookId)},
					{$push:updateValue}
				);
			} else {
			    if (arrayIndex >= 0) updateValue[param+"."+arrayIndex] = edit;
			    else updateValue[param] = edit;
			    book_collection.update(
			    	{_id:ObjectID.createFromHexString(bookId)}, 
			    	{$set:updateValue}
			    );
			}
			book_collection.update(
				{_id:ObjectID.createFromHexString(bookId)},
				{$set:{"last_edit": new Date() } }
			);
			callback(null, "Success");
    	}
  	});
Esempio n. 5
0
File: post.js Progetto: llaske/Twist
	delete: function(req, res) {
		// Check params
		var params = req;
		if (!params || !params.headers || !params.params) {
			res.status(400);
			res.send({'error': 'Invalid arguments'});
			return;
		}
		var uid = params.headers['uid'];
		var id = params.params.id;
		if (!uid || !mongo.ObjectID.isValid(uid)) {
			res.status(400);
			res.send({'error': 'Invalid arguments'});
			return;
		}
		if (!id || !mongo.ObjectID.isValid(id)) {
			res.status(400);
			res.send({'error': 'Invalid arguments'});
			return;
		}
		db.collection(postsCollection, function(err, collection) {
			collection.remove({'_id':new mongo.ObjectID(id), 'uid':uid}, function(err, result) {
				if (err) {
					res.status(400);
					res.send({'error':'An error has occurred'});
				} else {
					res.send({_id:id});
				}
			});
		});
	},
Esempio n. 6
0
File: mongo.js Progetto: donwb/yak
		conn.collection(collectionName, function objectWasInserted(err, coll){
			var lastMod = new Date();
			var created = new Date();
			if (object instanceof Array) {
				for(var i=0;i<object.length;i++){
					object[i].lastModified = lastMod;
					object[i].created = created;
					var id = mongodb.ObjectID.createPk();
					object[i]._id = id;  
				}
			}
			else{
				object.lastModified = lastMod;
				object.created = created;
				var id = mongodb.ObjectID.createPk();
				object._id = id;  	
			}
			coll.insert(object, function(err, docs){
				if(err){
					console.log('***** error when inserting into collection!:');
					console.log(err);
					throw err;
				}
				if(func){
					if(object instanceof Array){
            func(docs);
					}
					else{
            func(docs[0]);
					}
			  }
			});
		});
Esempio n. 7
0
File: post.js Progetto: llaske/Twist
// Private: get a twist
function getPost(params, callback) {
	// Get params
	if (!params || (!params.headers && !params.body) || !params.params) {
		callback();
		return;
	}
	var uid = (params.headers ? params.headers['uid'] : params.body.uid);
	var id = params.params.id;

	// Limit to an user
	var query = {};
	if (!uid || !mongo.ObjectID.isValid(uid)) {
		callback();
		return;
	}
	query.uid = uid;

	// Limit to a specific twist
	if (!id || !mongo.ObjectID.isValid(id)) {
		callback();
		return;
	}
	query._id = new mongo.ObjectID(id);

	// Retrieve twist matching
	db.collection(postsCollection, function(err, collection) {
		collection.findOne(query, function(err, item) {
			callback(item);
		});
	});
}
Esempio n. 8
0
 exports.deleteUser = function (req, res) {
  var userId = req.param("_id");

  if (!userId) {
    // Strange, I have no id. Lets send the home
    res.redirect('/');
  }
  else {
    var db = req.app.settings.db;
    console.log("userId:", userId);
    //var oid = new ObjectId.createFromHexString(userId);
    var oid = new ObjectId(userId);

    console.log("ObjectId.toHexString: ", oid.toHexString());
    
    db.collection('users', function(err, collection) {
      collection.remove({_id: oid}, {w:1}, function (err, result) {
        if (err) throw err;

        console.log("Result from removing a user: ", result);
        res.redirect('/admin/users');
      });
    });
    
  }
 };
Esempio n. 9
0
// posts
function createPosts(cb) {
    'use strict';

    var postCollection = db.collection('posts');
    var posts = importFile.posts;
    var i, max, y, max2, k, max3;
    for (i = 0, max = posts.length; i < max; i += 1) {
        posts[i]._id = ObjectID.createFromHexString(posts[i]._id);
        posts[i].author = ObjectID.createFromHexString(posts[i].author);
        posts[i].category = ObjectID.createFromHexString(posts[i].category);
        posts[i].created = new Date(posts[i].created);

        for (y = 0, max2 = posts[i].tags.length; y < max2; y += 1) {
            posts[i].tags[y]._id = ObjectID.createFromHexString(posts[i].tags[y]._id);
        }

        for (k = 0, max3 = posts[i].comments.length; k < max3; k += 1) {
            posts[i].comments[k]._id = ObjectID.createFromHexString(posts[i].comments[k]._id);
        }
    }

    postCollection.drop();
    postCollection.insert(posts, {safe: true}, function (err, res) {
        if (err) {
            console.error(err);
        }
        else {
            console.log('=======================');
            console.log('posts');
            console.log('=======================');
            console.log(res);
            cb(null);
        }
    });
}
Esempio n. 10
0
// comments
function createComments(cb) {
    'use strict';

    var commentCollection = db.collection('comments');
    var comments = importFile.comments;
    var i, max;
    for (i = 0, max = comments.length; i < max; i += 1) {
        comments[i]._id = ObjectID.createFromHexString(comments[i]._id);
        comments[i].author = ObjectID.createFromHexString(comments[i].author);
        comments[i].created = new Date(comments[i].created);
    }

    commentCollection.drop();
    commentCollection.insert(comments, {safe: true}, function (err, res) {
        if (err) {
            console.error(err);
        }
        else {
            console.log('=======================');
            console.log('comments');
            console.log('=======================');
            console.log(res);
            cb(null);
        }
    });
}
Esempio n. 11
0
		testData.insert(JSON.parse(query.data), {w:1}, function(err, result){
			fatalError(err);
			var newdid = new ObjectId(result[0]._id);
			var clist = [];
			clist.push(socket.id);
			addClient(newdid.toHexString(), clist);
			addDid(socket.id, newdid.toHexString());

			//INSERT INTO TEMP COLLECTION TO RERUN QUERIES
			tempData.insert(JSON.parse(query.data), {w:1}, function(temperr, tempresult){
				fatalError(err);
				logMessage("New objected added to tempData")
				socket.emit('create', {qid: query.qid, data: result[0], status: 'OK'});
				queryPool.forEach(function(value, key){
					var repeatQ = value.qString;
					var toNotify = value.clients;

					tempData.find(repeatQ.criteria).toArray(function(err, valNotify){
						fatalError(err);
						if (valNotify.length != 0){
							toNotify.forEach(function(entry){
								logMessage("Notifying client about new object: " + entry);
								if (subscribedTo.has(entry)){
									io.sockets.to(entry).emit('notify-new', {qid: key, data: valNotify[0], status: 'OK' });
								}	
							});
						}
						tempData.remove({}, {w:1}, function(rm_err, numRemoved){
							fatalError(rm_err);
							logMessage("New Obj removed from tempData");
						});
					});			
				});
			});
		});
Esempio n. 12
0
PostsModel.comment = function (alias_id, post_id, message, callback) {

  if (ObjectID.isValid(post_id) && message) {
    message.trim();
    var comment_data = {
      message: message,
      post_id: new ObjectID(post_id)
    }


    if (alias_id && ObjectID.isValid(alias_id)) {
      AliasModel.getAliasInfoForPost(alias_id, function (data) {
        comment_data.author = data;
        CommentsModel.save(comment_data, function (res) {
          if (res) {
            PostsModel.getPost(comment_data.post_id, function (doc) {
              var notice = AppModel.db.collection('notifications');
              notice.save({
                alias: data,
                post_data: doc,
                read: 0,
                type: 'comment',
                created_date: new Date()
              }, function (err, doc) {
                return callback(res.ops[0], doc.ops[0])
              })
            })
          } else {
            return callback({
              error: {
                message: [{
                  msg: "Could not save your comment, please try again",
                  type: 'warning'
                }]
              }
            })
          }
        })
      })
    } else {
      CommentsModel.save(comment_data, function (res) {
        if (res) {
          return callback({response: res})
        } else {
          return callback({error: {message: [{msg: "Could not save your comment, please try again", type: 'warning'}]}})
        }
      })
    }
  } else {
    return callback({
      error: {
        message: [{
          msg: "An unexpected error occured please try again latter, please try again",
          type: 'warning'
        }]
      }
    })
  }
}
     ', o segundo ObjectID, e iguais', function() {
    var objID1 = new ObjectID();
    var objID2 = objID1.toString();

    var saoIguais = compareObjectIDs(objID2, objID1);

    expect(saoIguais).to.be.equal(true);
  });
  it('Deve ser \'true\' se ambos parametros forem ObjectID e iguais', function() {
    var objID1 = new ObjectID();
    var objID2 = new ObjectID(objID1.toString());

    var saoIguais = compareObjectIDs(objID1, objID2);

    expect(saoIguais).to.be.equal(true);
  });
     ' apenas um parâmetro for fornecido', function() {
    var objID1 = new ObjectID();
    var objID2 = new ObjectID(objID1.toString());

    var saoIguais = compareObjectIDs(objID1)(objID2);

    expect(saoIguais).to.be.equal(true);
  });
Esempio n. 16
0
  deleteOptionValue(productId, optionId, valueId) {
    if(!ObjectID.isValid(productId) || !ObjectID.isValid(optionId) || !ObjectID.isValid(valueId)) {
      return Promise.reject('Invalid identifier');
    }

    return this.getOptionValuesWithDeletedOne(productId, optionId, valueId)
      .then(values => this.overwriteAllValuesForOption(productId, optionId, values))
      .then(updateResult => this.getOptionValues(productId, optionId))
  }
Esempio n. 17
0
 return new Promise(function(resolve,reject){
    var ObjectID = require('mongodb').ObjectID;
    var id = new ObjectID();
    self.params._id = id.toHexString();
    self.db.collection(self.collection).insert(self.params
 ,function(err,doc){
      if(err){reject(err);}
      self.results.push(doc);
      resolve(true);
    });
  });
Esempio n. 18
0
  addOptionValue(productId, optionId, data) {
    if(!ObjectID.isValid(productId) || !ObjectID.isValid(optionId)) {
      return Promise.reject('Invalid identifier');
    }
    let productObjectID = new ObjectID(productId);
    let optionObjectID = new ObjectID(optionId);

    const optionValueData = this.getValidDocumentForInsert(data);

    return mongo.db.collection('products').updateOne({
        _id: productObjectID, 'options.id': optionObjectID
      }, {$push: { 'options.$.values': optionValueData }}).then(res => this.getOptionValues(productId, optionId));
  }
Esempio n. 19
0
  updateOptionValue(productId, optionId, valueId, data) {
    if(!ObjectID.isValid(productId) || !ObjectID.isValid(optionId) || !ObjectID.isValid(valueId)) {
      return Promise.reject('Invalid identifier');
    }

    if(data.name !== undefined) {
      return this.getModifiedOptionValues(productId, optionId, valueId, data.name)
        .then(values => this.overwriteAllValuesForOption(productId, optionId, values))
        .then(updateResult => this.getOptionValues(productId, optionId))
    } else {
      return Promise.reject('Please, specify value name')
    }

  }
Esempio n. 20
0
 fDB.findOne(filterData, {f1: 1, f2: 1, e1: 1, e2: 1, s1: 1, s2: 1, dt: 1}, null, function (err, item) {
     if (err) {
         res.json({ok: 0})
     } else {
         var createDt = new Date(item.dt);
         var nowDt = new Date();
         if (createDt.getMonth() == nowDt.getMonth() && createDt.getDate() == nowDt.getDate()) {
             res.json({ok: 2})
         } else {
             var updateData = {};
             var updateFilterData = {};
             if (uid.toString() == item.f1.toString()) {
                 if (e) {
                     updateData = {e2: e}
                 }
                 if(s){
                     updateData = {s2:new Date().getTime()/1000}
                 }
                 updateFilterData = {f1: uid, f2: item.f2, zid: zid}
             } else if (uid.toString() == item.f2.toString()) {
                 if (e) {
                     updateData = {e1: e}
                 }
                 if(s){
                     updateData = {s1:new Date().getTime()/1000}
                 }
                 updateFilterData = {f2: uid, f1: item.f1, zid: zid}
             }
             updateData.dt = nowDt.getTime()
             fDB.updateOne(updateFilterData, {$set: updateData}, null, function (err) {
                 if (err) {
                     res.json({ok: 0})
                 } else {
                     //TODO 暂且体力领取设置为 10
                     if (e) {
                         function giveSuccessCallBack(){
                             res.json({ok: 1, d: updateData})
                         }
                         function giveFailCallBack(){
                             res.json({ok: 0})
                         }
                         var fUid = f1Id?f1Id:f2Id;
                         emailFunc.giveEnergy(req.body.uid, zid, fUid, fromName, 10,giveSuccessCallBack,giveFailCallBack)
                     }
                 }
             })
         }
     }
 })
Esempio n. 21
0
app.patch('/todos/:id', authenticate, (req, res) => {
  var id = req.params.id;
  var body = _.pick(req.body, ['text', 'completed']);

  if (!ObjectID.isValid(id)) {
    return res.status(404).send('Id is not valid');
  };

  if (_.isBoolean(body.completed) && body.completed) {
    body.completedAt = new Date().getTime();
  } else {
    body.completed = false;
    body.completedAt = null;
  }

  Todo.findOneAndUpdate({
    _id: id,
    _creator: req.user._id
  }, {$set: body}, {new: true}).then((todo) => {
    if (!todo) {
      return res.status(404).send();
    }

    res.send({todo});
  }).catch((e) => {
    res.status(400).send();
  })
});
Esempio n. 22
0
// users
function createUsers(cb) {
    'use strict';

    var userCollection = db.collection('users');
    var users = importFile.users;
    var i, max;
    for (i = 0, max = users.length; i < max; i += 1) {
        users[i]._id = ObjectID.createFromHexString(users[i]._id);
        users[i].birthdate = new Date(users[i].birthdate);
    }

    userCollection.drop();
    userCollection.insert(users, {safe: true}, function (err, res) {
        if (err) {
            console.error(err);
        }
        else {
            console.log('=======================');
            console.log('users');
            console.log('=======================');
            console.log(res);
            cb(null);
        }
    });
}
Esempio n. 23
0
 success: function(obj) {
     user = obj;
     req.mongo.collection('tournaments').findOne({_id: ObjectID.createFromHexString(data.tournament_id)}, function(err, item) {
         if (err == null && item) {
             tournament = item;
             req.mongo.collection('transactions').findOne({payment_id: data.payment_id}, function(err, transaction) {
                 if (err) {
                     raiseDbError(res, err);
                 }
                 else {
                     if (transaction && transaction.confirmed) {
                         for (var i in tournament.contestants) {
                             if (tournament.contestants[i].id == data.user_id) {
                                 tournament.contestants[i].paid = true;
                                 tournament.contestants[i].status = 'confirmed';
                                 tournament.contestants[i].transaction = transaction._id;
                                 tournament.contestants[i].venmo_id = transaction.venmo_id;
                                 
                                 req.mongo.collection('tournaments').save(tournament, function (err, result) {
                                     if (err) {
                                         raiseDbError(res, err);
                                         return;
                                     }
                                     res.status(200);
                                     res.send(res, JSON.stringify({
                                         transaction_id: transaction._id,
                                         status: 'confirmed'
                                     }));
                                     res.end(); 
                                 });
                                 return;
                             }
                         }
                     }
                     else if (transaction) {
                         raiseDbError(res, 'Payment in inconsistent state. Contact support.');
                     }
                     else {
                         req.mongo.collection('transactions').insert({
                             user_id: data.user_id,
                             payment_id: data.payment_id,
                             tournament_id: data.tournament_id,
                             venmo_id: null,
                             confirmed: false
                         }, function(err, result) {
                             res.status(200);
                             res.send(data.payment_id);
                         });
                     }
                 }
             });
         }
         else if (err) {
             raiseDbError(res, err);
         }
         else {
             raiseInvalidParametersException(res, 'Tournament does not exist.');
         }
     });
 },
Esempio n. 24
0
app.get('/validate', function(req, res) {
  // if we don't have an id, redirect to / with an error message
  // if we have a valid id, validate it, then redirect to / with a success message
  // if we don't have a valid id, redirect to / with an error message
  if (req.query.id) {
    var idstr = mongo.ObjectID.createFromHexString(req.query.id);
    announcements_db.findOne({ _id: idstr }, function(err, doc) {
      if (err || doc == null) {
        req.flash('warning', 'Invalid validation ID!');
        console.log("invalid validation id!");
      } else {
        console.log("queueing " + idstr);
        announcements_db.update({ _id: idstr }, 
          {$set: {status: "queued"}}, 
          function(err, doc) {
            if (err || doc == null) {
              req.flash('warning', 'Announce queueing failed?!');
              console.log("failed! " + err + doc);
            } else {
              req.flash('info', 'Announcement queued successfully!');
              io.sockets.emit('queued', req.query.id + " to queued");
              console.log("succeeded")
            }
          }
        );
      }
      res.redirect("/");
    });
  } else {
    console.log("warning");
    req.flash('warning', 'Invalid validation request?!');
    res.redirect("/");
  };
});
Esempio n. 25
0
    db.collection('reports', function(err, collection) {
      if (err) {
        mongodb.close();
        return callback(err);
      }

      var query = {};
      if (id) {
        query._id = ObjectId.createFromHexString(id);
      }
      
      collection.find(query).sort({time: -1}).toArray(function(err, docs) {
        mongodb.close();
        if (err) {
          callback(err, null);
        }

        var reports = [];
        docs.forEach(function(doc, index) {
          var report = new Report(doc.user, doc.report, doc.time, doc._id);
          
          reports.push(report);
        });
        callback(null, reports);
      });
    });
Esempio n. 26
0
router.patch('/:id', (req, res) => {
  var id = req.params.id;
  var body = _.pick(req.body, ['text', 'completed']);

  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }

  if (_.isBoolean(body.completed) && body.completed) {
    body.completedAt = new Date().getTime();
  } else {
    body.completed = false;
    body.completedAt = null;
  }

  Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
    if (!todo) {
      return res.status(404).send();
    }

    Todo.findById(id).then((todo) => {
      res.send(todo);
    });


    //res.send(todo);
  }).catch((e) => {
    res.status(400).send();
  })
});
Esempio n. 27
0
 app.get('/servitudes/:servId', function (req, res, next) {
     servColl
         .findOne({ _id: ObjectID.createFromHexString(req.params.servId) }, function (err, servitude) {
             if (err) return next(err);
             res.send(servitude);
         });
 });
Esempio n. 28
0
		function fixStringId(id) {
			if (id && ( typeof(id) === 'string' )) {
				return mongodb.ObjectID.createFromHexString(id);
			} else {
				return id;
			}
		}
Esempio n. 29
0
  router.patch('/scanResults/:id', (req, res) => {
    var id = req.params.id;
    if (!ObjectID.isValid(id)) {
      return res.status(400).send();
    }

    // Do something...
    /*var body = _.pick(req.body, ['propperty1', 'propperty2']);
    if (_.isBoolean(body.completed) && body.completed) {
        body.completedAt = new Date().getTime();
    } else {
        body.completed = false;
        body.completedAt = null;
    }*/

    ScanResult.findByIdAndUpdate(id, {
      $set: body
    }, {
      new: true
    }).then((scanResult) => {
      if (!scanResult) {
        return res.status(404).send();
      }
      res.status(200).send({
        scanResult
      });
    }).catch((dbError) => {
      res.status(400).send(dbError);
    })
  });
function makeid(hexstr) {
  if( _.isString(hexstr) && 24 == hexstr.length ) {
      return mongo.ObjectID.createFromHexString(hexstr)
  }

  return hexstr;
}