how to get data from existing mongo collection using parse server? - mongodb

I am new to Parse Server.
I am having an existing collection "users" in "employee" db in Mongodb.
I need to get the users data using Parse Server.
Below is the code:
var query = new Parse.Query(users);
query.find().then((data) => {
return data;
}).catch((error) => {
return error;
});
But I am getting the error "users" is not defined.
Need some valuable help.

if your Class really is called users (which is different to the built-in Parse Server Class called User), then use :
var query = new Parse.Query('users'); //note the quotation around 'users'
If you are in fact trying to query the built-in User class, use :
var query = new Parse.Query(Parse.User);
or
var query = new Parse.Query('_User');

Related

How to return and update a table in bookshelf knex

I am using postgresql, knex, and bookshelf to make queries to update my users table. I would like to find all users who didn't sign in during a specific time and then update their numAbsences and numTardies field.
However it appears that when running a raw sql query using bookshelf.knex the result that I get for users is an array of objects rather than an array of bookshelf objects of objects because I can't save the objects directly to the database when I try to use .save(). I get the exception user.save is not a function.
Does anyone know how I can update the values in the database for the users? I've seen the update function but I need to also return the users in absentUsers so I select them currently.
// field indicates whether the student was late or absent
var absentUsers = function(field){
// returns all users who did not sign in during a specific time
if (ongoingClasses){
return bookshelf.knex('users')
.join('signed_in', 'signed_in.studentId', '=', 'users.id')
.where('signed_in.signedIn', false)
.select()
.then(function(users){
markAbsent(users, field);
return users;
});
}
}
var markAbsent = function(users, field){
users.forEach(function(user){
user[field]++;
user.save();
})
}
I've solved my problem by using another sql query in knex. It seemed there was no way to use a sql query and then use standard bookshelf knex methods since the objects returned were not bookshelf wrapper objects.
var absentUsers = function(field){
// returns all users who did not sign in during a specific time
if (ongoingClasses){
return bookshelf.knex('users')
.join('signed_in', 'signed_in.studentId', '=', 'users.id')
.where('signed_in.signedIn', false)
.select()
.then(function(users){
markAbsent(users, field);
});
}
}
var markAbsent = function(users, field){
users.forEach(function(user){
var updatedUser = {};
updatedUser[field] = user[field]+1;
bookshelf.knex('users')
.where('users.id', user.id)
.update(updatedUser).then(function(){
});
});
}
With your code bookshelf.knex('users') you leave the "Bookshelf world" and are in "raw knex world". Knex alone doesn't know about your Bookshelf wrapper objects.
You may use Bookshelf query method to get the best of both worlds.
Assuming your model class is User, your example would look approximately like
User.query(function(qb) {
qb.join('signed_in', 'signed_in.studentId', 'users.id')
.where('signed_in.signedIn', false);
})
.fetchAll()
.then(function(bookshelfUserObjects) {
/*mark absent*/
return bookshelfUserObjects.invokeThen('save'); // <1>
});
<1> invokeThen: Call model method on each instance in collection

ReferenceError: db is not defined while trying to find distinct entries in database

I am getting db is not defined when trying to use mongodb's distinct in meteor.
Template.displayinbox.helpers({
inboxlistings: function() {
itemscount = db.Messages.distinct( "fromUsername" ).count;
return db.Messages.distinct( "fromUsername" );
}
});
I want to be able to return only distinct documents in my collection from the username field and count all those documents that is posted by the fromUsername. How would I go about doing this in Meteor?
When you're querying anything in the Meteor code itself, you don't need to write db first. You have to use the variable name that used to instantiate the Mongo Object. Let's say you defined your Mongo db like this.
example = new Mongo.Collection('Messages');
then within your helper you just use the typical query using this object.
Template.displayinbox.helpers({
inboxlistings: function() {
var items = example.find();
return _uniq(items,function(i){return i.fromUserName;});
}
});

How to take database name as variable

I am creating an app for employees using Meteor and MongoDB. This app will be used by multiple organizations. So I will make a separate DB for each organization. I am facing an issue in Meteor about how to keep database name and collection name as variable. Database name will be decided on login. Then I will keep DB name in Session.
Collection name can also be a variable.
For example:
var dbName = Session.get("dbName"); //for eg dbName="redex"
var collectionName = Session.get("collectionName"); // for ex collectionName="employees"
Employees = new Mongo.Collection(collectionName);
How to manage the variables in this case?
You will have to create a server method that creates a given database according to dbName and collectionName parameters:
'newDatabase': function (dbName, collectionName) {
var d = new MongoInternals.RemoteCollectionDriver(process.env.MONGO_URL.replace("originDB", dbName));
Employees = new Mongo.Collection(collectionName, { _driver: d });
}
You will also have to declare that new collection on your client side:
Meteor.call('newDatabase', Session.get("dbName"), Session.get("collectionName"), function (err, res) {
if (!err)
Employees = new Mongo.Collection(Session.get("collectionName"));
});

Convert all collection in a single db into new dbs

can you please help me,
I am trying to copy all collections in a particular database into create new database and move that collection into it.But the following code does not work. and my colleciton name in the db contains two part ' mg2.data' ,'mg32.data' i want to create new database mg2 and copy collection name as data.
collection name mg2.data suppose to be in mg2 database and collection name data.
db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
//print(dbName)
db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
}
});
Here is my situation details.
I am having Db name Master and it contains about 60-70 collections its names like(mg1.data,mg2.data,mg3.data)
and i want it to be like
db name mg1 and collection name data
db name mg2 and collection name data and so on..
i am facing the problem that when in the first design write operation locks entire database(Master). i cannot go for sharding and all now.
I got this approach working for me.I dont know is this best aproach
db.getCollectionNames().forEach(function( a ){
if(a!='system.indexes' ) {
var sp = a.split('.');
var dbName = sp[0];
var col = sp[1];
print(dbName+'\n');
//db[a].copyTo(db.getSiblingDB(dbName).getcCollection(col));
db[a].find().forEach(function(d){ db.getSiblingDB(dbName)[col].insert(d); });
}
});

Node + Mongoose: Get last inserted ID?

I want to retrieve the last inserted _id, using mongoose as MongoDB wrapper for node.js. I've found the following tutorial, but I can't change any node modules because the app runs on a public server:
Getting "Last Inserted ID" (hint - you have to hack Mongoose)
Any other ideas? This what I want to do:
Insert new user
Get user's _id value
Set a new session based on user's id
Redirect to /
Thanks!
I'm using mongoose version 1.2.0 and as soon as I created a new instance of a mongoose model, the _id is already set.
coffee> u = new User()
[object Object]
coffee> u._id
4dd68fc449aaedd177000001
I also verified that after I call u.save() the _id remains the same. I verified via MongoHub that this is indeed the real ID saved into MongoDB.
If you explicitly declare
_id: Schema.ObjectId
for your model, then the ObjectId will not be available after new or save.
This is probably a bug.
If you're looking to get the last inserted _id of a sub object, then create the object, and add it to the item. Here's an example in NowJS using MongoDB and Mongoose (to add some schema sugar) which then converts the result to JSON to send back to the client:
var nowRoomID = this.now.room;
var Conversation = mongoose.model('Conversation');
Conversation.findById(convID, function(error, conversation) {
var Blip = mongoose.model('Blip');
var createdBlip = new Blip();
createdBlip.author= nowUserName;
createdBlip.authorid = parsed.authorid;
createdBlip.body = revisedText;
createdBlip.created_at = new Date();
createdBlip.modified_at = new Date();
conversation.blips.push(createdBlip);
parsed._id = createdBlip._id; //NOTE: ID ACCESSED HERE
message = JSON.stringify(parsed);
conversation.save(function (err) {
if (!err) {
console.log('Success - saved a blip onto a conversation!');
nowjs.getGroup(nowRoomID).now.receiveMessage(nowUserName, message);
}
});
With MongoDB, if you don't explicitly set a document's _id value then the client driver will automatically set it to an ObjectId value. This is different from databases that might generate IDs on the server and need another query to retrieve it, like with SQL Server's scope_identity() or MySQL's last_insert_id().
This allows you to insert data asynchronously because don't need to wait for the server to return an _id value before you continue.
So, as shown is Peter's answer, the _id is available before the document is saved to the database.
I just get the id from the document passed to the callback, since save returns the saved document.
Check below url
http://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html
you will find following code in given url
var document = {name:"David", title:"About MongoDB"};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});