Is Mongodb stitch functions can use bulkwrite()? - javascript

I try to call collection.bulkWrite() in MongoDB stitch functions, but I get an error - “bulkWrite is not a function”. Is it possible to use bulkWrite() in MongoDB stitch functions?
Here is my stitch function - and I made it “run as a system”:
exports = function(arg){
var collection = context.services.get("mongodb-atlas").db("testDATABASE").collection("allSkuTable");
return collection.bulkWrite(some_paramets_inside);
};
What is the proper way to call bulkWrite() if it is even possible?

Related

Cant read data from collection in MongoDB Atlas Trigger

New to MongoDB, very new to Atlas. I'm trying to set up a trigger such that it reads all the data from a collection named Config. This is my attempt:
exports = function(changeEvent) {
const mongodb = context.services.get("Cluster0");
const db = mongodb.db("TestDB");
var collection = db.collection("Config");
config_docs = collection.find().toArray();
console.log(JSON.stringify(config_docs));
}
the function is part of an automatically created realm application called Triggers_RealmApp, which has Cluster0 as a named linked data source. When I go into Collections in Cluster0, TestDB.Config is one of the collections.
Some notes:
it's not throwing an error, but simply returning {}.
When I change context.services.get("Cluster0"); to something else, it throws an error
When I change "TestDB" to a db that doesnt exist, or "Config" to a collection which doesn't exist, I get the same output; {}
I've tried creating new Realm apps, manually creating services, creating new databases and new collections, etc. I keep bumping into the same issue.
The mongo docs reference promises and awaits, which I haven't seen in any examples (link). I tried experimenting with that a bit and got nowhere. From what I can tell, what I've already done is the typical way of doing it.
Images:
Collection:
Linked Data Source:
I ended up taking it up with MongoDB directly, .find() is asynchronous and I was handling it incorrectly. Here is the reply straight from the horses mouth:
As I understand it, you are not getting your expected results from the query you posted above. I know it can be confusing when you are just starting out with a new technology and can't get something to work!
The issue is that the collection.find() function is an asynchronous function. That means it sends out the request but does not wait for the reply before continuing. Instead, it returns a Promise, which is an object that describes the current status of the operation. Since a Promise really isn't an array, your statment collection.find().toArray() is returning an empty object. You write this empty object to the console.log and end your function, probably before the asynchronous call even returns with your data.
There are a couple of ways to deal with this. The first is to make your function an async function and use the await operator to tell your function to wait for the collection.find() function to return before continuing.
exports = async function(changeEvent) {
const mongodb = context.services.get("Cluster0");
const db = mongodb.db("TestDB");
var collection = db.collection("Config");
config_docs = await collection.find().toArray();
console.log(JSON.stringify(config_docs));
};
Notice the async keyword on the first line, and the await keyword on the second to last line.
The second method is to use the .then function to process the results when they return:
exports = function(changeEvent) {
const mongodb = context.services.get("Cluster0");
const db = mongodb.db("TestDB");
var collection = db.collection("Config");
collection.find().toArray().then(config_docs => {
console.log(JSON.stringify(config_docs));
});
};
The connection has to be a connection to the primary replica set and the user log in credentials are of a admin level user (needs to have a permission of cluster admin)

Function is not recognized in map reduce command, mongoDB (javascript)

I have some problems with a map reduce I tried to do in MongoDB. A function I defined seems to not be visible in the reduce function.
This is my code:
function getName(user_id){
var users = db.users.aggregate({$project:{"_id":"$_id", "name":"$name"}});
users.forEach((it) => {if (user_id == it._id) return it.name;});
return "user not found";
}
var mapFunc = function(){ emit(this.user_id, this.book_id) };
var reduceFunc = function(key, values){return getName(key);};
db.booksToRecover.mapReduce(mapFunc, reduceFunc, {out:'users_to_recover_books_from'});
This is what I get:
The function was defined in the locally running javascript instance, not the server.
In order for that function to be callable from the server you will need to either predefine it there or include the definition inside the reduce function.
But don't do that.
From the reduce function documentation:
The reduce function should not access the database, even to perform read operations.
Look at using aggregation with a $lookup stage instead.

How to unit test a function that is calling other functions?

I am testing my REST API with jest for the first time and I am having a hard time unit testing the controllers.
How should I go about testing a function that contains other function calls (npm modules as well as other controllers). Here's pseudo code. (I've tried mocking but can't seem to get it right)
async insertUser(uid, userObject){
// Function to check user role and permissions
const isAllowed = await someotherController.checkPermissions(uid);
//Hash password using an npm module
const pass = password.hash;
//const user = new User(userObj)
user.save();
}
So basically, how to test such a function that contains all these different functions.
I have written tests for simple function and they went all good but I am stuck at these functions.
I would go with https://sinonjs.org/ and mock somecontroller. Be carefull with the user.save(). It looks like you use some kind of persistence here. In case you use mongoose, you should have a look at https://github.com/Mockgoose/Mockgoose.

How to make api request with callback as argument in node.js?

I want to use method getPlayers(callback) which is defined as:
getPlayers(callback)
callback - Required. Called with an object of players
players - An object containing all the players connected to the server, with their name as the key
Retrieve all players connected to the server.
Here is the link to complete module for further details :
https://www.npmjs.com/package/hltv-livescore#getplayerscallback
If you want to use it and access the data, you'll need to do something like this:
getPlayers(function(players) {
// Here your players will be available
console.log(players)
})
Bonus: If you're using ES6, you can use Arrow functions, that are more elegant, like this (single line):
getPlayers(players => console.log(players))
or (multi line):
getPlayers(players => {
console.log(players)
})
You can read more about the async nature of Javascript here
If you refer source code of npm package you can see this code
https://github.com/andrewda/hltv-livescore/blob/master/lib/index.js#L78
Livescore.prototype.getPlayers = function(callback) {
callback(self.players);
};
You can use getPlayers like this :
Livescore.getPlayers(function(players){
// you will get players here
});

How can i use sinon to stub functions for neo4j Thingdom module

I am having some issues writing some unit tests where i would like to stub out the functionality of the neo4j Thingdom module.
After a few hours of failed attempts i have been searching around the web and the only point of reference i found was a sample project which used to sinon.createStubInstance(neo4j.GraphDatabase); to stub out the entire object. For me, and becuase this seemed to a be a throw away project i wanted a more fine grained approach so i can test that for instance as the Thingdom API outlines when saving a node you create it (non persisted) persist it and then you can index it if you wish which are three calls and could be outlined in multiple specific tests, which i am not sure can be achieved with the createStubInstance setup (i.e. found out if a function was called once).
Example "create node" function (this is just to illustrate the function, i am trying to build it out using the tests)
User.create = function(data, next){
var node = db.createNode(data);
node.save(function(err, node){
next(null,node);
});
};
I am able to stub functions of the top level object (neo4j.GraphDatabase) so this works:
it('should create a node for persistence', function(){
var stub = sinon.stub(neo4j.GraphDatabase.prototype, 'createNode');
User.create({}, res);
stub.calledOnce.should.be.ok;
stub.restore();
});
The issue comes with the next set of test i wish to run which tests if the call to persist the node to the database is called (the node,save) method:
I am not sure if this is possible or it can be achieved but i have tried several variations of the stub and non seem to work (on neo4j.Node, neo4j.Node.prototype) and they all come back with varying errors such as can't wrap undefined etc. and this is probably due to the createNode function generating the node and not my code directly.
Is there something i am glaringly doing wrong, am i missing the trick or can you just not do this? if not what are the best tactics to deal with stuff like this?
A possible solution is to return a stubbed or mocked object, giving you control on what happens after the node is created:
it('should create a node for persistence and call save', function () {
var stubbedNode = {
save: sinon.stub().yields(undefined, stubbedNode)
};
var stub = sinon.stub(neo4j.GraphDatabase.prototype, 'createNode').returns(stubbedNode);
User.create({}, res);
stub.calledOnce.should.be.ok;
stub.restore();
stubbedNode.save.calledOnce.should.be.ok;
});
We couldn't do it directly, the way the module is setup it doesn't work to well with Sinon. What we are doing is simply abstracting the module away and wrapping it in a simple facade/adapter which we are able to stub on our unit tests.
As we are not doing anything bar calling the neo4j module in that class we are integration (and will validate when regression testing) testing that part to make sure we are hitting the neo4j database.

Categories

Resources