How to access results within batch statements in oriento - orientdb

How do I access the newly inserted #rid in my second batch statement. I need to be able to access the #rid from the first statement.
var member = {
'email': 'test#test.com',
'id': 200,
'lastupdated': new Date()
};
db
.let('insert', function (s) {
s
.insert().into('member')
.set(member)
})
.let('update', function (s) {
s
.update('#12:74')
.set({
'from': '$insert'['#rid'] // how do I access the #rid from the previous statement
})
})
.commit()
.return('$update')
.all()
.then(function (results) {
console.log(results);
})
.done();

I had the same problem a couple of days ago. Finally, it turned out that the syntax in the case of a link is as follows:
.set('from=$insert')
Cheers

Related

Optional chaining of methods like sort, limit, skip

I'm passing the query params and there could be any combination of sort, limit or skip for the Mongoose Query.
What I've thought of is to create mutliple mongoose queries based on what params have been passed. So if only sort is passed then the resulting query will have Document.find({}).sort({}) and incase only limit is passed then query would be Document.find({}).limit({})
Should I write something like this -
router.get('/', (req, res) => {
if(req.query.sortByPrice) {
Property.find({})
.sort({ price: req.query.sortByPrice === 'asc' ? 1 : -1 })
.populate('user_id', 'name')
.exec((err, properties) => {
if (err)
return res
.status(404)
.json({ error: "Can't get user details!" });
res.status(200).json(properties);
});
}
if(req.query.limit) {
Property.find({})
.limit(req.query.limit)
.populate('user_id', 'name')
.exec((err, properties) => {
if (err)
return res
.status(404)
.json({ error: "Can't get user details!" });
res.status(200).json(properties);
});
}
});
You can create a variable options from your request body and pass it as the third argument to the .find() query, no need to write redundant code with if-else block.
Secnd argument to .find() query is projection, so don't forget to pass an empty object there.
Try this :
let options={};
if(req.query.sortByPrice){
options.sort = {
price: req.query.sortByPrice === 'asc' ? 1 : -1
}
}
if(req.query.limit){
options.limit = req.query.limit
}
Property.find({},{},options)
.populate('user_id', 'name')
.exec((err, properties) => {
if (err)
return res
.status(404)
.json({ error: "Can't get user details!" });
res.status(200).json(properties);
return;
});
Note: Dont forget to return after res.status().json(), otherwise you might get error cant set headers after they are sent . if you try to send response again.

In mongo how to get the current position of the record in the table with the total records for pagination?

I'm trying to return create a paginated list. I used graphql to query the data. With my query, I pass the number of records I need (In a variable named first) and the ID of the last fetched record (In a varible called after). Now I managed to write a query (Note that I used mongoose) to fetch the records. Now what I need to do is get the relavant information to perform the pagination like hasNextPage, hasPreviousPage, currentPage and totalPages.
To get most of these information I need to get the total number of records in the database. To do that I need to send another db request.
I also need to know the position of the record in the table. No idea how.
Here's the query:
new Promise((resolve, reject) =>
Company.where('_id')
.gt(after)
.limit(first)
.lean()
.exec((error, doc) => {
if (error) {
reject(error);
}
resolve({
edges: doc,
pageInfo: {
hasNextPage: '...',
hasPreviousPage: '...',
currentPage: '...',
totalPages: '...'
}
});
}))
Any idea how to do this efficiently?
you can try this module mongoose-paginate
here what i uses, for pagination,
var current = req.query.filter.current;
var limit = req.query.filter.limit;
console.log('params.query.filter.current',current);
var skip = Number(limit)*Number(current)-Number(limit);
console.log('skip::',skip);
Cours.find({'attributes.version.status': true}).skip(skip).limit(limit).sort({_id:'asc'}).exec(function (err, resulta) {
if (err) {
console.log('erreur trouverCours');
res.json({
protecteds: err
});
}
console.log('cours ::', resulta);
res.json({
"data": resulta
});
});

What is the syntax for a mongoose query where I just want one property's value?

I am sending a query to mongoDB using mongoose. The collection is named Step. I want the result of this query to be an array of _id values, one per step. Currently I am getting all of the step objects in their entirety, because req.query isn't defined in this case.
service:
this.getSteps = function() {
return $http({
method: 'GET',
url: '/api/step'
})
.then(function(response) {
return response.data;
});
};
controller:
readStep: function (req, res) {
Step.find(req.query, function(err, result) {
if (err) {
res.status(500).send(err);
}
res.status(200).send(result);
});
}
Set the second parameter of the find query to '_id' to retrieve only the _id of the objects.
Step.find(req.query, '_id', function(err, result) {
This will return data like this:
[{_id: 123}, {_id: 234}]
If you want to get an array of the Step ids on their own, use the javascript map function like so
result = result.map(function(doc) {
return doc._id;
});
which will give you an array like this:
[123, 234]
You'll need to use query.select, something like as shown below:
Step.find(query).select({ "_id": 1}).then(....);
I'm not able to type much because I'm responding from my handheld.
Hope this help!

Query with waterline and sails JS

I am using SailsJS with waterline.
My user model has_many bookings. I need to get all users that have passed more than 3 bookings in the last months.
I managed to write a query that gets all users that made a booking in the last month.
findUsersWhoBookedLastMonth: function(cb){
var dateM30J = moment().subtract(30,'days').format();
console.log(dateM30J);
Reservation.find({
select: ['user'],
where:{
date:{
'>=' : dateM30J
}
},
}, function(err, user_ids) {
if (err) {
console.log('ERROR: ' + err);
cb(err, null)
}
else {
user_ids = _.uniq(user_ids);
cb(null, user_ids)
}
});
},
but i can't figure out how to get all users that have booked more than three times in the last month
Your Reservation.find(...) returns an array, just check for each user if the array size is > 3.
Or you can use .count(), it has the same effect.

Is there a way to query MongoDB Rest API with a list or array of IDs

I'm using a MEAN stack and with Mongoose. Is there a way to query MongoDB with multiple ids to only return those specific IDs in one query e.g. /api/products/5001,5002,5003
Is this possible or would I need to query each product individually or add an additional attribute to the products and query by that.
Update: To clarify as suggested below I've managed to get it partially working using {'_id': { $in: [5001,5002,5003]} however I'm having problems figuring out how to pass the list from the api url to the find function.
Using Express.js for router
router.get('/list/:ids', controller.showByIDs);
exports.showByIDs = function(req, res) {
Product.find({'_id': { $in: [req.params.ids]}}, function (err, product) {
if(err) { return handleError(res, err); }
if(!product) { return res.send(404); }
return res.json(product);
})
};
Then trying /api/products/list/5001 works however /api/products/list/5001,5002 doesn't. I'm not sure if it's a syntax problem in the url or my router code that needs to change or the controller.
You can use the $in operator to query for multiple values at once:
Products.find({_id: {$in: [5001, 5002, 5003]}}, function (err, products) { ... });
On the Express side, you need to use a format for the ids parameter that lets you split it into an array of id values, like you had in your first example:
/api/products/5001,5002,5003
Then in your route handler, you can call the split function on the req.params.ids string to turn it into an array of id values that you can use with $in:
exports.showByIDs = function(req, res) {
var ids = req.params.ids.split(',');
Product.find({'_id': { $in: ids}}, function (err, product) {
if(err) { return handleError(res, err); }
if(!product) { return res.send(404); }
return res.json(product);
})
};