Best JavaScript code snippet using ava
server.js
Source:server.js
...153app.use(bodyparser.urlencoded( { extended: true } ));154app.use(bodyparser.json());155// edit profile156app.get("/api/fetchuserdetail", function(req, res) {157 mongoose.connect("mongodb://localhost/angprojdb");158 Signup.find( {Username: req.query.uname},function(err, data) {159 if (err) {160 console.log(err);161 res.send(err);162 } else {163 console.log(data);164 res.send(data);165 }166 mongoose.connection.close();167 });168});169// Contact us170app.post("/api/contactus", function(req, res) {171 mongoose.connect("mongodb://localhost/angprojdb");172 var newcontactus = new Contactus(173 {174 Name: req.body.nm1,175 Email: req.body.em1,176 Phone: req.body.ph1,177 Message: req.body.msg178});179 newcontactus.save(function(err) {180 if (err) {181 res.send("Error while signing up, try again");182 } else {183 console.log(err);184 res.send("Query Sent");185 }186 mongoose.connection.close();187 });188});189// Signup190app.post("/api/signup", function(req, res) {191 mongoose.connect("mongodb://localhost/angprojdb");192 var newsignup = new Signup(193 {194 Name:req.body.nm,195 Gender:req.body.gen,196 Phone:req.body.ph,197 Username: req.body.em,198 Password: req.body.pass,199 Usertype: req.body.utype200 });201 newsignup.save(function(err) {202 if (err) {203 console.log(err);204 res.send("Error while signing up!");205 } else {206 res.send("Signup Successful");207}208 mongoose.connection.close();209 });210});211// Login212app.post("/api/login", function(req, res) {213 mongoose.connect("mongodb://localhost/angprojdb");214 console.log(req.body);215 Signup.find({ Username:req.body.username,Password:req.body.pass}, function(err, data)216 {217 if (err)218 {219 console.log(err);220 res.send(err);221 }222 else223 {224 console.log(data);225 res.send(data);226 }227 mongoose.connection.close();228 });229});230// Change Password231app.put("/api/changepassword", (req, res) => {232 mongoose.connect("mongodb://localhost/angprojdb");233 Signup.updateOne({234 Username: req.body.un,235 Password: req.body.cpass236 },237 {238 $set:239 {240 Password: req.body.newp241 }242 },243 (err, data) => {244 if (err) {245 console.log(err);246 res.send("Failed to Change the Password")247 } else res.send(data);248 });249 mongoose.connection.close();250});251// Search userInfo by email252app.post("/api/srchusr", function(req, res) {253 mongoose.connect("mongodb://localhost/angprojdb");254 console.log(req.query);255 Signup.find({ Username:req.query.em}, function(err, data)256 {257 if (err)258 {259 console.log(err);260 res.send(err);261 }262 else263 {264 console.log(data);265 res.send(data);266 }267 mongoose.connection.close();268 });269 });270 // All users info271 app.get("/api/alluser", function(req, res) {272 mongoose.connect("mongodb://localhost/angprojdb");273 console.log(req.query);274 Signup.find(function(err, data) {275 if (err) {276 console.log(err);277 res.send(err);278 } else {279 console.log(data);280 res.send(data);281 }282 mongoose.connection.close();283 });284});285// Delete user286app.delete("/api/delmemb", (req, res) => {287 mongoose.connect("mongodb://localhost/angprojdb");288 console.log(req.query);289 Signup.remove ({ _id: req.query.id}, function(err, data) {290 if (err) {291 console.log(err);292 res.send("Failed");293 } else {294 console.log(data);295 res.send("Successfully Deleted");296 }297 mongoose.connection.close();298 });299});300// Insert Category301app.post("/api/managecat", upload.single("photo"), (req, res) => {302 mongoose.connect("mongodb://localhost/angprojdb");303 if (!req.file) {304 picname = "noimagefound.png";305 }306 var newmanagecat = new managecat({Catname: req.body.catname, Catpic: picname});307 newmanagecat.save( function(err) {308 if (err) {309 console.log(err);310 res.send("Failed");311 } else {312 res.send("Successfully Inserted");313 }314 mongoose.connection.close();315 });316})317 // fetch categories318 app.get("/api/fetchcategories", function(req, res) {319 mongoose.connect("mongodb://localhost/angprojdb");320 managecat.find(function(err, data) {321 if (err) {322 console.log(err);323 res.send(err);324 } else {325 console.log(data);326 res.send(data);327 }328 mongoose.connection.close();329 });330});331// Fetch sub-categories332 app.get("/api/fetchsubcategories", function(req, res) {333 mongoose.connect("mongodb://localhost/angprojdb");334 managesubcat.find({Catid: req.query.catid}, function(err, data) {335 if (err) {336 console.log(err);337 res.send(err);338 } else {339 console.log(data);340 res.send(data);341 }342 mongoose.connection.close();343 });344});345// Update categories346app.put("/api/updatecat", upload.single('photo'),function(req, res) {347 mongoose.connect("mongodb://localhost/angprojdb");348 //var d = new Date();349 if (!req.file)350 {351 picname = req.body.oldpic;352 }353 else354 {355 if(req.body.oldpic != "noimagefound.png")356 {357 fs.unlink('src/uploads/' + req.body.oldpic, (err) => {358 if (err) throw err;359 console.log('file was deleted');360 });361 }362 }363 managecat.update({ _id: req.body.cid }, { $set: {Catname: req.body.catname, Catpic: picname}},function(err) {364 if (err)365 {366 console.log(err);367 res.send("Failed");368 }369 else370 {371 res.send("Successfully Updated");372 }373 mongoose.connection.close();374 });375 });376 // Delete Category along with Sub-cat and products377// -------------------------------------------------378 app.delete("/api/delcat", function(req, res) {379 mongoose.connect("mongodb://localhost/angprojdb");380 managecat.remove({_id: req.query.id}, function(err, data) {381 if (err) {382 console.log(err);383 res.send(err);384 } else {385 console.log(data);386 res.send("Successfully deleted")387 }388 mongoose.connection.close();389 });390});391app.delete("/api/delsubcat", function(req, res) {392 mongoose.connect("mongodb://localhost/angprojdb");393 managesubcat.remove({Catid: req.query.id}, function(err, data) {394 if (err) {395 console.log(err);396 res.send(err);397 } else {398 console.log(data);399 res.send("Successfully deleted")400 }401 mongoose.connection.close();402 });403});404app.delete("/api/delproducts", function(req, res) {405 mongoose.connect("mongodb://localhost/angprojdb");406 manageproduct.remove({catId: req.query.id}, function(err, data) {407 if (err) {408 console.log(err);409 res.send(err);410 } else {411 console.log(data);412 res.send("Successfully deleted")413 }414 mongoose.connection.close();415 });416});417// -------------------------------------------------418app.delete("/api/delsubcatbyid", function(req, res) {419 mongoose.connect("mongodb://localhost/angprojdb");420 managesubcat.remove({_id: req.query.id}, function(err, data) {421 if (err) {422 console.log(err);423 res.send(err);424 } else {425 console.log(data);426 res.send("Successfully deleted")427 }428 mongoose.connection.close();429 });430});431app.delete("/api/delproductsbysubid", function(req, res) {432 mongoose.connect("mongodb://localhost/angprojdb");433 manageproduct.remove({subcatId: req.query.id}, function(err, data) {434 if (err) {435 console.log(err);436 res.send(err);437 } else {438 console.log(data);439 res.send("Successfully deleted")440 }441 mongoose.connection.close();442 });443});444 // Insert Sub-category445 app.post("/api/addsubcat",upload.single('photo'), function(req, res)446{447 mongoose.connect("mongodb://localhost/angprojdb");448 //var d = new Date();449 if (!req.file)450 {451 picname="noimagefound.png";452 };453 var newmanagesubcat = new managesubcat( {Catid:req.body.cid, Subcatname:req.body.scatname,Subcatpic:picname} );454 newmanagesubcat.save(function(err) {455 if (err)456 {457 console.log(err);458 res.send("Failed");459 }460 else461 {462 res.send("Successfully Inserted");463 }464 mongoose.connection.close();465 });466});467// Update subcategory468//update sub-categories469app.put("/api/updatesubcat", upload.single('photo'),function(req, res) {470 mongoose.connect("mongodb://localhost/angprojdb");471 //var d = new Date();472 if (!req.file)473 {474 picname=req.body.oldpic;475 }476 else477 {478 if(req.body.oldpic!="noimagefound.png")479 {480 fs.unlink('src/uploads/' + req.body.oldpic, (err) => {481 if (err) throw err;482 console.log('file was deleted');483 });484 }485 }486 managesubcat.update({ _id: req.body.scid }, { $set: {Catid:req.body.catid, Subcatname: req.body.scatname, Subcatpic:picname}},function(err) {487 if (err)488 {489 console.log(err);490 res.send("Failed");491 }492 else493 {494 res.send("Successfully Updated");495 }496 mongoose.connection.close();497 });498});499// Add product500app.post("/api/addproduct",upload.single('photo'), function(req, res)501{502 mongoose.connect("mongodb://localhost/angprojdb");503 // var d = new Date();504 if (!req.file)505 {506 picname="noimagefound.png";507 };508 var newmanageproduct = new manageproduct(509 {510 catId: req.body.cid,511 subcatId: req.body.subcatid,512 Name: req.body.pname,513 Price: req.body.prate,514 Desc: req.body.pdesc,515 Discount: req.body.pdiscount,516 Stock: req.body.pstock,517 Image: picname518 });519 newmanageproduct.save(function(err) {520 if (err)521 {522 console.log(err);523 res.send("Failed");524 }525 else526 {527 res.send("Successfully Inserted");528 }529 mongoose.connection.close();530 });531});532// Fetch products based on their respective catid and subcatid533app.get("/api/fetchproducts", function(req, res) {534 mongoose.connect("mongodb://localhost/angprojdb");535 manageproduct.find({536 subcatId: req.query.subcat537 }, function(err, data) {538 if (err)539 {540 console.log(err);541 res.send(err);542 } else {543 console.log(data);544 res.send(data);545 }546 mongoose.connection.close();547 })548});549// Fetch products based on their respective catid and subcatid550app.get("/api/fetchproductsforhome", function(req, res) {551 mongoose.connect("mongodb://localhost/angprojdb");552 manageproduct.find({553 subcatId: req.query.subcat554 }, function(err, data) {555 if (err)556 {557 console.log(err);558 res.send(err);559 } else {560 console.log(data);561 res.send(data);562 }563 mongoose.connection.close();564 }).limit(4)565});566// Fetch product details567app.get("/api/fetchproddetails", function(req, res) {568 mongoose.connect("mongodb://localhost/angprojdb");569 manageproduct.find({_id: req.query.pid}, function(err, data)570 {571 if (err)572 {573 console.log(err);574 res.send(err);575 }576 else577 {578 console.log(data);579 res.send(data);580 }581 mongoose.connection.close();582 });583});584//Update Products585app.put("/api/updateProduct", upload.single('photo'),function(req, res) {586 mongoose.connect("mongodb://localhost/angprojdb");587 //var d = new Date();588 if (!req.file)589 {590 picname=req.body.oldpic;591 }592 else593 {594 if(req.body.oldpic!="noimagefound.png")595 {596 fs.unlink('src/uploads/' + req.body.oldpic, (err) => {597 if (err) throw err;598 console.log('file was deleted');599 });600 }601 }602 manageproduct.update({ _id: req.body.prodid }, { $set: {catId:req.body.cid,subcatId:req.body.subcatid,Name:req.body.pname,Price:req.body.prate,Desc:req.body.pdesc, Discount:req.body.pdiscount, Stock:req.body.pstock, Image:picname}},function(err) {603 if (err)604 {605 console.log(err);606 res.send("Failed");607 }608 else609 {610 res.send("Successfully Updated");611 }612 mongoose.connection.close();613 });614});615 // Delete product616 app.delete("/api/delprod", function(req, res) {617 mongoose.connect("mongodb://localhost/angprojdb");618 console.log(req.query)619 manageproduct.remove({ _id: req.query.id}, function(err, data) {620 if (err) {621 console.log(err);622 res.send("Failed");623 } else {624 console.log(data);625 res.send("Successfully Deleted");626 }627 mongoose.connection.close();628 });629});630app.delete("/api/delsubcat", function(req, res) {631 mongoose.connect("mongodb://localhost/angprojdb");632 console.log(req.query)633 managesubcat.remove({ _id: req.query.id}, function(err, data) {634 if (err) {635 console.log(err);636 res.send("Failed");637 } else {638 res.send("Success");639 console.log(data);640 }641 mongoose.connection.close();642});643});644app.delete("/api/delprodbysub", function(req, res) {645 mongoose.connect("mongodb://localhost/angprojdb");646 console.log(req.query)647 manageproduct.remove({ subcatId: req.query.subid}, function(err, data) {648 if (err) {649 console.log(err);650 res.send("Failed");651 } else {652 res.send("Successfully Deleted Sub-category and its respective products");653 console.log(data)654 }655 mongoose.connection.close();656});657});658// Add cart659app.post("/api/addcart", function(req, res) {660 mongoose.connect("mongodb://localhost/angprojdb");661 var newcart = new cart( {prodid:req.body.prodid,pname:req.body.pname,prate:req.body.prate,qt:req.body.qt,tc:req.body.tc,ppic:req.body.ppic,username:req.body.username} );662 newcart.save(function(err) {663 if (err)664 {665 console.log(err);666 res.send("Error while adding to cart, try again");667 }668 else669 {670 res.send("Added to cart successfully");671 }672 mongoose.connection.close();673 });674});675//get cart products from showcart component676app.get("/api/fetchcart", function(req, res) {677 mongoose.connect("mongodb://localhost/angprojdb");678 console.log(req.query);679 cart.find({ username:req.query.uname }, function(err, data)680 {681 if (err)682 {683 console.log(err);684 res.send("Failed");685 }686 else687 {688 console.log(data);689 res.send(data);690 mongoose.connection.close();691 }692 });693 });694 //delete cart products from show cart products695app.delete("/api/deletecartprod", function(req, res) {696 mongoose.connect("mongodb://localhost/angprojdb");697 console.log(req.query);698 cart.remove({ _id: req.query.id }, function(err, data)699 {700 if (err)701 {702 console.log(err);703 res.send("Failed");704 }705 else706 {707 console.log(data);708 res.send("Successfully Deleted");709 mongoose.connection.close();710 }711 });712 });713//get order number for ordersuccess component714app.post("/api/checkout", function(req, res) {715 mongoose.connect("mongodb://localhost/angprojdb");716 d = new Date();717 var newcheckout = new checkout(718 {719 orderamount:req.body.billtot, address:req.body.add,username:req.body.un,orderdate: d, paymentmode: req.body.pmode, status: 'processing',720 cardno: req.body.cardno,companyName: req.body.coname,holdername: req.body.hname, expdate: req.body.expdt, cvvno: req.body.cvv721 });722 newcheckout.save(function(err, data) {723 if (err)724 {725 console.log(err);726 }727 else728 {729 res.send(data);730 }731 mongoose.connection.close();732 })733 });734 //get order number for ordersuccess component735app.get("/api/getordernum", function(req, res) {736 mongoose.connect("mongodb://localhost/angprojdb");737 checkout.find({ username: req.query.un }, function(err, data) {738 if (err)739 {740 console.log(err);741 res.send("Failed");742 }743 else744 {745 console.log(data);746 res.send(data);747 }748 mongoose.connection.close();749 }).sort({"orderdate":-1});750});751// all user's orders752app.get("/api/getallorderdetails", function(req, res) {753 mongoose.connect("mongodb://localhost/angprojdb");754 checkout.find(function(err, data) {755 if (err)756 {757 console.log(err);758 res.send("Failed");759 }760 else761 {762 console.log(data);763 res.send(data);764 }765 mongoose.connection.close();766 }).sort({"orderdate":-1});767});768// Get cart by username769app.get("/api/getcart", function(req, res) {770 mongoose.connect("mongodb://localhost/angprojdb");771 console.log(req.query);772 cart.find({username:req.query.un}, function(err, data)773 {774 if (err)775 {776 console.log(err);777 res.send("Failed");778 }779 else780 {781 console.log(data);782 res.send(data);783 }784 mongoose.connection.close();785 });786});787// Insert order details for ordersuccess component788app.post("/api/orderitems",function(req,res)789{790mongoose.connect("mongodb://localhost/angprojdb");791var neworder=req.body;792order.insertMany(neworder, function (err, docs) {793 if (err){794 return console.error(err);795 } else {796 console.log("Multiple documents inserted to Collection");797 res.send("Successfully inserted");798 }799 mongoose.connection.close();800 });801});802// Update stock after the successful of order803app.put("/api/updatestock",function(req,res){804 mongoose.connect("mongodb://localhost/angprojdb");805 var updatelist=req.body;806 for(let x=0;x<updatelist.length;x++)807 {808 manageproduct.updateOne({_id:updatelist[x].pid},{$inc: {"S tock":-updatelist[x].qty}},function(err,data){809 if (err)810 {811 console.log(err);812 res.send("Failed");813 } else814 {815 console.log(data);816 }817 mongoose.connection.close();818 });819 }820 res.send("Successfully Updated");821});822// empty cart after transaction823app.delete("/api/emptycart", function(req, res) {824 mongoose.connect("mongodb://localhost/angprojdb");825 cart.remove({ username:req.query.un }, function(err, data) {826 if (err)827 {828 console.log(err);829 res.send("Failed");830 }831 else832 {833 console.log(data);834 res.send("removed to cart successfully");835 }836 mongoose.connection.close();837 });838});839// Get order details by user840app.get("/api/getorderdetailsbyuser", function(req, res) {841 mongoose.connect("mongodb://localhost/angprojdb");842 order.find({ orderid: req.query.orderid }, function(err, data) {843 if (err)844 {845 console.log(err);846 res.send("Failed");847 }848 else849 {850 console.log(data);851 res.send(data);852 }853 mongoose.connection.close();854 });855});856app.get("/api/getorderdetailbyordernum", function(req, res) {857 mongoose.connect("mongodb://localhost/angprojdb");858 checkout.find({ username: req.query.uname }, function(err, data) {859 if (err)860 {861 console.log(err);862 res.send("Failed");863 }864 else865 {866 console.log(data);867 res.send(data);868 }869 mongoose.connection.close();870 });871});872// update status873app.put("/api/updateStatus", function(req, res) {874 mongoose.connect("mongodb://localhost/angprojdb");875 checkout.updateOne({ _id: req.body.orderid}, { $set: { status: req.body.newstatus}}, function(err, data) {876 if (err)877 {878 console.log(err);879 res.send("Failed");880 }881 else882 {883 console.log(data);884 res.send("Status updated");885 }886 mongoose.connection.close();887 });888});889// fetch messages890app.get("/api/fetchContactusmessages", function(req, res) {891 mongoose.connect("mongodb://localhost/angprojdb");892 Contactus.find(function(err, data) {893 if (err)894 {895 console.log(err);896 res.send(err);897 } else {898 console.log(data);899 res.send(data);900 }901 mongoose.connection.close();902 })903});904// edit profile905app.put("/api/editprofile", function(req, res) {906 mongoose.connect("mongodb://localhost/angprojdb");907 Signup.updateOne({ Username: req.body.oldem}, { $set: { Name: req.body.nm, Phone: req.body.ph, Username: req.body.em}}, function(err, data) {908 if (err)909 {910 console.log(err);911 res.send("Failed");912 }913 else914 {915 console.log(data);916 res.send(data);917 }918 mongoose.connection.close();919 });920});921app.get("/api/fetchproductbysearch",function(req,res) {922 mongoose.connect("mongodb://localhost/angprojdb");923 console.log(req.query);924 console.log("hello");925 // db.users.find(name: new RegExp(search));926 // ({name: { $regex: '.' + name + '.' } }).limit(5);927 var pname=req.query.querysearch;928 manageproduct.find({Name: { $regex: '.*' + pname ,$options:'i' }}, function(err,data){929 if(err)930 {931 console.log(err);932 res.send("No result found");933 }934 else935 {936 console.log(data);...
index.js
Source:index.js
1'use strict';2const config = require('config');3const mongoose = require('mongoose');4const model = require('../../../src/model');5const UserSchema = require('../../../src/model/user');6const EventSchema = require('../../../src/model/event');7const ChatSchema = require('../../../src/model/chat');8describe('src/model/index', () => {9 const sandbox = sinon.createSandbox();10 beforeEach(() => {11 sandbox.stub(config, 'get').withArgs('mongo').returns({12 user: 'some-user',13 password: 'some-password',14 host: 'some-host',15 port: 9999,16 database: 'some-db'17 });18 sandbox.stub(mongoose, 'connect');19 sandbox.stub(mongoose, 'model');20 sandbox.stub(console, 'error');21 });22 afterEach(() => {23 delete process.env.MONGO_USER;24 delete process.env.MONGO_PASSWORD;25 sandbox.restore();26 });27 describe('initialize', () => {28 it('should use configured user for db connection', () => {29 return model.initialize().then(() => {30 assert.calledOnce(mongoose.connect);31 assert.calledWithMatch(mongoose.connect, /some-user/);32 });33 });34 it('should use configured password for db connection', () => {35 return model.initialize().then(() => {36 assert.calledOnce(mongoose.connect);37 assert.calledWithMatch(mongoose.connect, /some-password/);38 });39 });40 it('should use configured host for db connection', () => {41 return model.initialize().then(() => {42 assert.calledOnce(mongoose.connect);43 assert.calledWithMatch(mongoose.connect, /some-host/);44 });45 });46 it('should use configured port for db connection', () => {47 return model.initialize().then(() => {48 assert.calledOnce(mongoose.connect);49 assert.calledWithMatch(mongoose.connect, /9999/);50 });51 });52 it('should use configured database for db connection', () => {53 return model.initialize().then(() => {54 assert.calledOnce(mongoose.connect);55 assert.calledWithMatch(mongoose.connect, /some-db/);56 });57 });58 describe('should also override from environment variable', () => {59 it('user', () => {60 process.env.MONGO_USER = 'some-env-user';61 return model.initialize().then(() => {62 assert.calledOnce(mongoose.connect);63 assert.calledWithMatch(mongoose.connect, /some-env-user/);64 });65 });66 it('password', () => {67 process.env.MONGO_PASSWORD = 'some-env-password';68 return model.initialize().then(() => {69 assert.calledOnce(mongoose.connect);70 assert.calledWithMatch(mongoose.connect, /some-env-password/);71 });72 });73 });74 it('should connect via valid connection string', () => {75 return model.initialize().then(() => {76 assert.calledOnce(mongoose.connect);77 assert.calledWith(78 mongoose.connect,79 'mongodb://some-user:some-password@some-host:9999/some-db'80 );81 });82 });83 describe('db connection failed', () => {84 beforeEach(() => {85 mongoose.connect.rejects(new Error('some connection error'));86 });87 it('should print error into console', () => {88 return model.initialize().catch(() => {89 assert.calledTwice(console.error);90 assert.calledWith(console.error.firstCall, 'Database connection error');91 assert.calledWith(console.error.secondCall, 'some connection error');92 });93 });94 /*95 it('should throw error', () => {96 return model.initialize().catch((error) => {97 console.log(error);98 assert.calledWith(error.message, 'Database connection error');99 });100 });101 */102 });103 describe('initialize models', () => {104 it('should initialize user model', () => {105 return model.initialize().then(() => {106 assert.calledWith(mongoose.model, 'User', UserSchema);107 });108 });109 it('should initialize event model', () => {110 return model.initialize().then(() => {111 assert.calledWith(mongoose.model, 'Event', EventSchema);112 });113 });114 it('should initialize chat model', () => {115 return model.initialize().then(() => {116 assert.calledWith(mongoose.model, 'Chat', ChatSchema);117 });118 });119 });120 it('should return object with initialized model classes', () => {121 const userModel = sinon.stub();122 const eventModel = sinon.stub();123 const chatModel = sinon.stub();124 mongoose.model.withArgs('User').returns(userModel);125 mongoose.model.withArgs('Event').returns(eventModel);126 mongoose.model.withArgs('Chat').returns(chatModel);127 return model.initialize().then((result) => {128 assert.instanceOf(result, Object);129 assert.equal(result.User, userModel);130 assert.equal(result.Event, eventModel);131 assert.equal(result.Chat, chatModel);132 });133 });134 });...
md-seed-runner.js
Source:md-seed-runner.js
1import { Subject } from 'rxjs';2import {3 getObjectWithSelectedKeys,4 normalizeSeederName,5} from '../utils/helpers';6import MdSeedRunnerError from './md-seed-runner-error';7/**8 * mongoose-data-seed runner9 */10export default class MdSeedRunner {11 /**12 * MdSeedRunner operations constants13 * @type {Object}14 * @property {string} START MdSeedRunner starts.15 * @property {string} SUCCESS MdSeedRunner succeed.16 * @property {string} ERROR MdSeedRunner finished with an error.17 */18 static operations = {19 START: 'START',20 SUCCESS: 'SUCCESS',21 ERROR: 'ERROR',22 MONGOOSE_CONNECT_START: 'MONGOOSE_CONNECT_START',23 MONGOOSE_CONNECT_SUCCESS: 'MONGOOSE_CONNECT_SUCCESS',24 MONGOOSE_CONNECT_ERROR: 'MONGOOSE_CONNECT_ERROR',25 MONGOOSE_DROP_START: 'MONGOOSE_DROP_START',26 MONGOOSE_DROP_SUCCESS: 'MONGOOSE_DROP_SUCCESS',27 MONGOOSE_DROP_ERROR: 'MONGOOSE_DROP_ERROR',28 ALL_SEEDERS_START: 'ALL_SEEDERS_START',29 ALL_SEEDERS_FINISH: 'ALL_SEEDERS_FINISH',30 SEEDER_START: 'SEEDER_START',31 SEEDER_SUCCESS: 'SEEDER_SUCCESS',32 SEEDER_ERROR: 'SEEDER_ERROR',33 };34 /**35 * Creates MdSeedRunner36 * @param {Function<Promise>} connect Connect to mongodb implementation37 * @param {Function<Promise>} dropdb Drop/Clear the database implementation38 * @param {Map<string, Function>} seedersList key=Seeder name | value=Seeder implementation39 */40 constructor({ connect, dropdb, seedersList }) {41 this.connect = connect;42 this.dropdb = dropdb;43 this.seedersList = seedersList;44 this._subject = new Subject();45 }46 run({ selectedSeeders = [], dropDatabase = false } = {}) {47 this._run({ selectedSeeders, dropDatabase });48 return this._subject.asObservable();49 }50 /*51 Private methods52 */53 async _run({ selectedSeeders, dropDatabase }) {54 const { START, SUCCESS, ERROR } = MdSeedRunner.operations;55 try {56 this._subject.next({57 type: START,58 payload: { selectedSeeders, dropDatabase },59 });60 await this._connectToMongodb();61 if (dropDatabase) {62 await this._dropDatabase();63 }64 await this._runSeeders(selectedSeeders);65 this._subject.next({66 type: SUCCESS,67 payload: { selectedSeeders, dropDatabase },68 });69 this._subject.complete();70 } catch (error) {71 const { type = ERROR, payload = { error } } = error;72 this._subject.error({ type, payload });73 }74 }75 async _connectToMongodb() {76 const {77 MONGOOSE_CONNECT_START,78 MONGOOSE_CONNECT_SUCCESS,79 MONGOOSE_CONNECT_ERROR,80 } = MdSeedRunner.operations;81 try {82 this._subject.next({ type: MONGOOSE_CONNECT_START });83 await this.connect();84 this._subject.next({ type: MONGOOSE_CONNECT_SUCCESS });85 } catch (error) {86 throw new MdSeedRunnerError({ type: MONGOOSE_CONNECT_ERROR, error });87 }88 }89 async _dropDatabase() {90 const {91 MONGOOSE_DROP_START,92 MONGOOSE_DROP_SUCCESS,93 MONGOOSE_DROP_ERROR,94 } = MdSeedRunner.operations;95 try {96 this._subject.next({ type: MONGOOSE_DROP_START });97 await this.dropdb();98 this._subject.next({ type: MONGOOSE_DROP_SUCCESS });99 } catch (error) {100 throw new MdSeedRunnerError({ type: MONGOOSE_DROP_ERROR, error });101 }102 }103 async _runSeeders(selectedSeeders) {104 const { ALL_SEEDERS_START, ALL_SEEDERS_FINISH } = MdSeedRunner.operations;105 const seeders = this._loadSelectedSeeders(selectedSeeders);106 this._subject.next({107 type: ALL_SEEDERS_START,108 payload: { seeders: Object.keys(seeders) },109 });110 for (const [name, Seeder] of Object.entries(seeders)) {111 await this._runSeeder({ name, Seeder });112 }113 this._subject.next({114 type: ALL_SEEDERS_FINISH,115 payload: { seeders: Object.keys(seeders) },116 });117 }118 async _runSeeder({ Seeder, name }) {119 const {120 SEEDER_START,121 SEEDER_SUCCESS,122 SEEDER_ERROR,123 } = MdSeedRunner.operations;124 try {125 this._subject.next({126 type: SEEDER_START,127 payload: { name },128 });129 const seeder = new Seeder();130 const results = await seeder.seed();131 this._subject.next({ type: SEEDER_SUCCESS, payload: { name, results } });132 } catch (error) {133 throw new MdSeedRunnerError({134 type: SEEDER_ERROR,135 payload: { name },136 error,137 });138 }139 }140 _loadSelectedSeeders(selectedSeeders) {141 if (selectedSeeders && selectedSeeders.length > 0) {142 return getObjectWithSelectedKeys(143 this.seedersList,144 selectedSeeders.map(name => normalizeSeederName(name))145 );146 }147 return this.seedersList;148 }...
Using AI Code Generation
1var mongoose = require('mongoose');2var mongoose = require('mongoose');3var mongoose = require('mongoose');4var mongoose = require('mongoose');5var mongoose = require('mongoose');6var mongoose = require('mongoose');7var mongoose = require('mongoose');8var mongoose = require('mongoose');9var mongoose = require('mongoose');10var mongoose = require('mongoose');11var mongoose = require('mongoose');12var mongoose = require('mongoose');13var mongoose = require('mongoose');14var mongoose = require('mongoose');15var mongoose = require('mongoose');16var mongoose = require('mongoose');
Using AI Code Generation
1var mongoose = require('mongoose');2var Cat = mongoose.model('Cat', { name: String });3var kitty = new Cat({ name: 'Zildjian' });4kitty.save(function (err) {5 console.log('meow');6});
Using AI Code Generation
1const mongoose = require('mongoose');2}).then(() => {3 console.log('Connected to MongoDB');4}).catch((err) => {5 console.log('Error connecting to MongoDB', err);6});7const User = mongoose.model('User', {8 name: {9 },10 age: {11 },12 email: {13 }14});15const newUser = new User({
Using AI Code Generation
1 .once('open', () => console.log('Good to go!'))2 .on('error', (error) => {3 console.warn('Warning', error);4 });5 if (error) {6 console.warn('Warning', error);7 } else {8 console.log('Good to go!');9 }10});11 .then(() => console.log('Good to go!'))12 .catch((error) => {13 console.warn('Warning', error);14 });15const Schema = mongoose.Schema;16const userSchema = new Schema({17});18To create a model, we will use the mongoose.model() method
Using AI Code Generation
1var mongoose = require('mongoose');2var Schema = mongoose.Schema;3var ObjectId = Schema.ObjectId;4var UserSchema = new Schema({5});6var User = mongoose.model('User', UserSchema);7var user = new User({
Using AI Code Generation
1const mongoose = require('mongoose');2const config = require('./config.json');3mongoose.connect(config.connectionString, {useNewUrlParser: true});4const db = mongoose.connection;5db.on('error', console.error.bind(console, 'connection error:'));6db.once('open', function() {7 console.log("Connected to DB");8});9const kittySchema = new mongoose.Schema({10});11const Kitten = mongoose.model('Kitten', kittySchema);12const silence = new Kitten({ name: 'Silence' });13silence.save(function (err, silence) {14 if (err) return console.error(err);15});16const fluffy = new Kitten({ name: 'fluffy' });17fluffy.save(function (err, fluffy) {18 if (err) return console.error(err);19});20Kitten.find(function (err, kittens) {21 if (err) return console.error(err);22 console.log(kittens);23})24Kitten.find({ }, 'name', function (err, kittens) {25 if (err) return console.error(err);26 console.log(kittens);27})28Kitten.find({ name: /^fluff/ }, 'name', function (err, kittens) {29 if (err) return console.error(err);30 console.log(kittens);31})32Kitten.find({ name: 'fluffy' }, 'name', function (err, kittens) {33 if (err) return console.error(err);34 console.log(kittens);35})36Kitten.find({ name: 'fluffy' }, 'name', function (err, kittens) {37 if (err) return console.error(err);38 console.log(kittens);39})
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!