How to query and update document by using single query? - node.js

I have documents likes the following:
{
"_id": "538584aad48c6cdc3f07a2b3",
"startTime": "2014-06-12T21:30:00.000Z",
"endTime": "2014-06-12T22:00:00.000Z",
},
{
"_id": "538584b1d48c6cdc3f07a2b4",
"startTime": "2014-06-12T22:30:00.000Z",
"endTime": "2014-06-12T23:00:00.000Z",
}
As you can see the documents above have startTime and endTime. I need to update some document that don't overlap others. I can make things to work by using two queries:
var event_id = "538584b1d48c6cdc3f07a2b4";
var event = {
startTime: "2014-06-12T21:30:00.000Z"
endTime: "2014-06-12T23:30:00.000Z"
};
Model.count({
_id: {$ne: event_id },
"$or": [
{"$and": [
{"startTime":{"$lte":event.startTime},"endTime":{"$gt":event.startTime}},
{"startTime":{"$lte":event.endTime},"endTime":{"$lt":event.endTime}}
]},
{"$and":[
{"startTime":{"$lte":event.startTime},"endTime":{"$gte":event.startTime}},
{"startTime":{"$lte":event.endTime},"endTime":{"$gte":event.endTime}}
]}
]
}, function (err, count) {
if (err) return next(err);
if (count) {
return next(new Error('Event overlapping'));
}
return Model.findOneAndUpdate({_id: event_id}, event, function (err, event) {
if (err) return next(err);
return res.json(200, event);
});
});
As you can see from the code above I do first query for checking of existing event that could overlaps. And then I do update.
Is it possible to make updating by using single query?

Related

mongoose not updating doc inside async.eachSeries

I am trying to update a doc inside async.eachSeries. But it does not update and I am not getting any error. See the code below.
I want to update the oldest doc, namely field LastDatePresent in that doc with the newest date present in both docs. So I have two duplicate docs based on UrlLink, and I want to update the oldest doc based on _id with the newest date in both docs. Example docs:
{
"_id": "older id",
"Date": ISODate("2017-08-25T00:00:00.000Z"),
"UrlLink": "www.myurl.com"
"LastDatePresent": ISODate("2017-08-30T00:00:00.000Z") //Should be updated to "LastDatePresent": ISODate("2017-08-31T00:00:00.000Z")
}
{
"_id": "newer id",
"Date": ISODate("2017-08-25T00:00:00.000Z"),
"UrlLink": "www.myurl.com"
"LastDatePresent": ISODate("2017-08-31T00:00:00.000Z")
}
Thankful for any suggestions:
async.eachSeries(aggres, function(member, callback2) {
myTable.find({
"UrlLink": member.UrlLink,
"Date": member.Date,
}, {
_id: 1,
UrlLink: 1,
Date: 1,
LastDatePresent: 1
}, {
sort: {
'_id': 1
}
}, function(err, post) {
var latestdate = post[0].LastDatePresent > post[1].LastDatePresent ? post[0].LastDatePresent : post[1].LastDatePresent;
myTable.update({
"UrlLink": post[0].UrlLink,
"Date": post[0].Date
}, {
$set: {
LastDatePresent: latestdate //NOT UPDATING HERE!
}
},
function(err, result) {
console.log("saving DATA");
callback2();
});
});
}, function(err) {
console.log("DONE");
});

How to update a array value in Mongoose

I want to update a array value but i am not sure about the proper method to do it ,so for i tried following method but didnt worked for me.
My model,
The children field in my model
childrens: {
type: Array,
default: ''
}
My query,
Employeehierarchy.update({ _id: employeeparent._id} ,{ $set: {"$push": { "childrens": employee._id }} })
.exec(function (err, managerparent) {});
Can anyone please provide me help.Thanks.
You can't use both $set and $push in the same update expression as nested operators.
The correct syntax for using the update operators follows:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
where <operator1>, <operator2> can be from any of the update operators list specified here.
For adding a new element to the array, a single $push operator will suffice e.g. you can use the findByIdAndUpdate update method to return the modified document as
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{ "$push": { "childrens": employee._id } },
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
Using your original update() method, the syntax is
Employeehierarchy.update(
{ "_id": employeeparent._id},
{ "$push": { "childrens": employee._id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);
in which the callback function receives the arguments (err, raw) where
err is the error if any occurred
raw is the full response from Mongo
Since you want to check the modified document, I'd suggest you use the findByIdAndUpdate function since the update() method won't give you the modified document, just the full write result from mongo.
If you want to update a field in the document and add an element to an array at the same time then you can do
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{
"$set": { "name": "foo" },
"$push": { "childrens": employee._id }
}
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
The above will update the name field to "foo" and add the employee id to the childrens array.
can follow this
if childrens contains string values then model can be like:
childrens: [{
type : String
}]
if childrens contains ObjectId values of another collection _id and want populate then model can be like:
childrens: [{
type : mongoose.Schema.Types.ObjectId,
ref: 'refModelName'
}]
no need to use $set just use $push to insert value in childrens array. so query can be like:
Employeehierarchy.update(
{ _id: employeeparent._id},
{"$push": { "childrens": employee._id } }
).exec(function (err, managerparent) {
//
});
This will help I guess
Employeehierarchy.findOneAndUpdate(
{ _id:employeeparent._id },
{ $set: { "childrens": employee._id }}
)

How to $set new Date() in MongoDB?

I have tried quite a few combinations and checked the MongoDB 3.2 docs, but I still am not getting my new Date() stored in my DB. Everything else below is getting properly stored. Thanks in advance for any tips!
Code from my app.js file:
db.collection('users').update({user: req.user.username}, {
$push: {
"recentPlays": {
"quiz": req.session.mostRecentQuiz,
"score": score
}
}
},{
$set: {
"mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
"mostRecentQuiz.time" : new Date() // StackOverflow: this is the part that is not getting stored in the DB.
}
}, function (err, result) {
if (err) throw err;
console.log(result);
});
Your update method is being called the wrong way, the update operators $set and $push should be in the same document. Re-write your method as:
db.collection('users').update(
{ "user": req.user.username },
{
"$push": {
"recentPlays": {
"quiz": req.session.mostRecentQuiz,
"score": score
}
}
"$set": {
"mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
"mostRecentQuiz.time" : new Date()
}
}, function (err, result) {
if (err) throw err;
console.log(result);
}
);

create a new object Id in mongoDB using node js

I am using the below code to insert data to mongodb
router.post('/NewStory', function (req, res) {
var currentObject = { user: userId , story : story , _id:new ObjectID().toHexString() };
req.db.get('clnTemple').findAndModify({
query: { _id: req.body.postId },
update: { $addToSet: { Stories: currentObject } },
upsert: true
});
});
This code is working fine if i remove the _id:new ObjectID().toHexString()
What i want to achieve here is that for every new story i want a unique _id object to be attached to it
What am i doing wrong?
{
"_id": {
"$oid": "55ae24016fb73f6ac7c2d640"
},
"Name": "some name",
...... some other details
"Stories": [
{
"userId": "105304831528398207103",
"story": "some story"
},
{
"userId": "105304831528398207103",
"story": "some story"
}
]
}
This is the document model, the _id that i am trying to create is for the stories
You should not be calling .toHexString() on this as you would be getting a "string" and not an ObjectID. A string takes more space than the bytes of an ObjectId.
var async = require('async'),
mongo = require('mongodb'),
db = require('monk')('localhost/test'),
ObjectID = mongo.ObjectID;
var coll = db.get('junk');
var obj = { "_id": new ObjectID(), "name": "Bill" };
coll.findAndModify(
{ "_id": new ObjectID() },
{ "$addToSet": { "stories": obj } },
{
"upsert": true,
"new": true
},
function(err,doc) {
if (err) throw err;
console.log(doc);
}
)
So that works perfectly for me. Noting the "new" option there as well so the modified document is returned, rather than the original form of the document which is the default.
{ _id: 55c04b5b52d0ec940694f819,
stories: [ { _id: 55c04b5b52d0ec940694f818, name: 'Bill' } ] }
There is however a catch here, and that is that if you are using $addToSet and generating a new ObjectId for every item, then that new ObjectId makes everything "unique". So you would keep adding things into the "set". This may as well be $push if that is what you want to do.
So if userId and story in combination already make this "unique", then do this way instead:
coll.findAndModify(
{
"_id": docId,
"stories": {
"$not": { "$elemMatch": { "userId": userId, "story": story } }
}
},
{ "$push": {
"stories": {
"userId": userId, "story": story, "_id": new ObjectID()
}
}},
{
"new": true
},
function(err,doc) {
if (err) throw err;
console.log(doc);
}
)
So test for the presence of the unique elements in the array, and where they do not exist then append them to the array. Also noting there that you cannot do an "inequality match" on the array element while mixing with "upserts". Your test to "upsert" the document should be on the primary "_id" value only. Managing array entries and document "upserts" need to be in separate update operations. Do not try an mix the two, otherwise you will end up creating new documents when you did not intend to.
By the way, you can generate an ObjectID just using monk.
var db = monk(credentials.database);
var ObjectID = db.helper.id.ObjectID
console.log(ObjectID()) // generates an ObjectID

Using $in in MongooseJS with nested objects

I've been successfully using $in in my node webservice when my mongo arrays only held ids. Here is sample data.
{
"_id": {
"$oid": "52b1a60ce4b0f819260bc6e5"
},
"title": "Sample",
"team": [
{
"$oid": "52995b263e20c94167000001"
},
{
"$oid": "529bfa36c81735b802000001"
}
],
"tasks": [
{
"task": {
"$oid": "52af197ae4b07526a3ee6017"
},
"status": 0
},
{
"task": {
"$oid": "52af197ae4b07526a3ee6017"
},
"status": 1
}
]
}
Notice that tasks is an array, but the id is nested in "task", while in teams it is on the top level. Here is where my question is.
In my Node route, this is how I typically deal with calling a array of IDs in my project, this works fine in the team example, but obviously not for my task example.
app.get('/api/tasks/project/:id', function (req, res) {
var the_id = req.params.id;
var query = req.params.query;
models.Projects.findById(the_id, null, function (data) {
models.Tasks.findAllByIds({
ids: data._doc.tasks,
query: query
}, function(items) {
console.log(items);
res.send(items);
});
});
});
That communicates with my model which has a method called findAllByIds
module.exports = function (config, mongoose) {
var _TasksSchema = new mongoose.Schema({});
var _Tasks = mongoose.model('tasks', _TasksSchema);
/*****************
* Public API
*****************/
return {
Tasks: _Tasks,
findAllByIds: function(data, callback){
var query = data.query;
_Tasks.find({_id: { $in: data.ids} }, query, function(err, doc){
callback(doc);
});
}
}
}
In this call I have $in: data.ids which works in the simple array like the "teams" example above. Once I nest my object, as with "task" sample, this does not work anymore, and I am not sure how to specify $in to look at data.ids array, but use the "task" value.
I'd like to avoid having to iterate through the data to create an array with only id, and then repopulate the other values once the data is returned, unless that is the only option.
Update
I had a thought of setting up my mongo document like this, although I'd still like to know how to do it the other way, in the event this isn't possible in the future.
"tasks": {
"status0": [
{
"$oid": "52995b263e20c94167000001"
},
{
"$oid": "529bfa36c81735b802000001"
}
],
"status1": [
{
"$oid": "52995b263e20c94167000001"
},
{
"$oid": "529bfa36c81735b802000001"
}
]
}
You can call map on the tasks array to project it into a new array with just the ObjectId values:
models.Tasks.findAllByIds({
ids: data.tasks.map(function(value) { return value.task; }),
query: query
}, function(items) { ...
Have you try the $elemMatch option in find conditions ? http://docs.mongodb.org/manual/reference/operator/query/elemMatch/

Resources