Mongodb findOneAndUpdate is not working - mongodb

I'm trying to update document in mongodb collection but it's not working for me. Here is the function all fields are come to the backend. I use mlab online mongo db
router.post(
'/accept',
(req,res) => {
const leaveFields = {};
leaveFields._id = req.body.id;
leaveFields.name = req.body.name;
leaveFields.reason = req.body.reason;
leaveFields.from = req.body.from;
leaveFields.to = req.body.to;
leaveFields.user_id = req.body.user_id;
leaveFields.leaveType = req.body.leaveType;
console.log(req.body.id);
Leave.find({user_id:req.body.user_id}) //{ "_id":ObjectId("req.body.id") }
.then(leave =>{
if(leave){
Leave.findOneAndUpdate(
{_id : req.body.id},
{$set : leaveFields},
{new : true}
)}else{
res.status(400).json(errors);
}
}
)
.catch(err=>res.status(404).json({ noleavefound: 'No leaves found' }));

Here you are setting _id to leavefields object and
const leaveFields = {};
leaveFields._id = req.body.id;
here you are passing _id field also to your update.
{$set : leaveFields}
_id field is an immutable filed. So, Exclude _id field and then check.

Related

Delete mongo recored by the timestamp in its id

This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.
How do I delete a recored, say created 30 days ago, using this gist?
const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
const db = <your-database>
db.messages.remove({_id : {$lt : deletionDate}});
The above returns a CastError
What would work, and as Ive said, I do not have a createdAt field:
db.messages.remove({createdAt : {$lt : deletionDate}});
Use mongo shell:
db.collection.find({"_id": { "$gt": ObjectId.fromDate(new Date('2017-10-01'))}})
Use mongoose:
Model.find({ _id: { $gt: mongoose.Types.ObjectId.createFromTime(new Date('2018-01-01')) } })
will find the needed docs.
var id = new ObjectId( Math.floor(deletionDate .getTime() / 1000).toString(16) + "0000000000000000")
db.messages.remove({createdAt : {$lt : id}});
You need to extract the timestamp from the object _id. So you could do something like:-
db.messages.find({}).forEach(function(rec) {
var recDate = rec._id.getTimestamp();
// Then here cast your deletionDate and recDate to preferred string format, e.g:-
var recDateString = recDate.getMonth()+1+'-'+recDate.getDate()+'-'+recDate.getFullYear();
var deletionDateString = deletionDate.getMonth()+1+'-'+deletionDate.getDate()+'-'+deletionDate.getFullYear();
if (deletionDateString == recDateString ){
db.messages.remove({_id:rec._id});
}
}

Why does MongoDB increase _id by one when inserting with custom id value

I am having some weird issue when inserting a new document with a custom _id value. If i insert a document with a custom _id of 1020716632230383 it gets saved in the database as 1020716632230384. For some reason it is incremented by 1.
what may cause this?
My query is :
exports.register = function(req, res){
console.log('ATTEMPT to register a user with id: ' + req.body.userInfo.id);
// prints 1020716632230383 !!!
var query = {'_id': req.body.userInfo.id};
var update = {
'_id': req.body.userInfo.id ,
'name': req.body.userInfo.name
};
var options = {
upsert: true,
setDefaultsOnInsert : true
};
User.findOneAndUpdate(query, update, options).exec(function(err ,doc){
if(!err){
console.log('REGISTERED!: ' , doc);
res.status(200).json({'success': true, 'doc': doc});
}else{
console.log(err);
res.status(200).json({'success': false});
}
});
};
In my Schema the _id is defined to be a number.
_id: {type:Number}
it is because "setDefaultsOnInsert : true" . when you use this option you can't update "_id" field. it is setting by mongoose.
if you want have a custom "_id" be sure "setDefaultsOnInsert" option is "false".
it is one of problems in mongoose .

Meteor queries not working with Meteor.Collection.ObjectID

I'm having a lot of trouble getting query results for certain collections in Meteor.
I have set
idGeneration : 'MONGO'
in the collection definitions, and in the mongo shell these collections look like this :
the document i want, call it documentW (from CollectionA) = {
"_id" : ObjectId("7032d38d35306f4472844be1"),
"product_id" : ObjectId("4660a328bd55247e395edd23"),
"producer_id" : ObjectId("a5ad120fa9e5ce31926112a7") }
documentX (from collection "Products") = {
_id : ObjectId("4660a328bd55247e395edd23")
}
documentY (from collection "Producers") = {
_id : ObjectId("a5ad120fa9e5ce31926112a7")
}
If i run a query like this in Meteor
CollectionA.findOne({ product_id : documentX._id, producer_id : documentY._id})
I'm expecting to get my documentW back... but I get nothing.
When I run this query in the mongo shell
db.collectiona.find({ product_id : ObjectId("4660a328bd55247e395edd23"), producer_id :
ObjectId("a5ad120fa9e5ce31926112a7") })
I get my documentW back no problem.
Of course in Meteor if I call
console.log(documentX._id)
I get this
{ _str : "4660a328bd55247e395edd23" }
Anyone have any ideas what is going on here ? I have tried all kinds of things like
Meteor.Collection.ObjectID(documentX._id._str)
but the search still returns empty...
Running the latest 0.7.0.1 version of Meteor...
I don't know if this answers your question, but I can't put this code in a comment. This code is working for me, trying to follow what I believe you are trying to do:
Products = new Meteor.Collection("products", {
idGeneration: "MONGO"
});
Producers = new Meteor.Collection("producers", {
idGeneration: "MONGO"
});
CollectionA = new Meteor.Collection("a", {
idGeneration: "MONGO"
});
Products.insert({
foo: "bar"
});
Producers.insert({
fizz: "buzz"
});
var documentX = Products.findOne();
var documentY = Producers.findOne();
CollectionA.insert({
product_id: documentX._id,
producer_id: documentY._id
});
var documentW = CollectionA.findOne({
product_id: documentX._id,
producer_id: documentY._id
});
console.log(documentW); // This properly logs the newly created document
This is on 0.7.0.1. Do you see anything in your code that diverges from this?

Mongodb, getting the id of the newly pushed embedded object

I have embedded comments in a posts model. I am using mongoosejs. After pushing a new comment in a post, I want to access the id of the newly added embedded comment. Not sure how to get it.
Here is how the code looks like.
var post = Post.findById(postId,function(err,post){
if(err){console.log(err);self.res.send(500,err)}
post.comments.push(comment);
post.save(function(err,story){
if(err){console.log(err);self.res.send(500,err)}
self.res.send(comment);
})
});
In the above code, the id of the comment is not returned. Note there is a _id field which is created in the db.
The schema looks like
var CommentSchema = new Schema({
...
})
var PostSchema = new Schema({
...
comments:[CommentSchema],
...
});
A document's _id value is actually assigned by the client, not the server. So the _id of the new comment is available right after you call:
post.comments.push(comment);
The embedded doc pushed to post.comments will have its _id assigned as it's added, so you can pull it from there:
console.log('_id assigned is: %s', post.comments[post.comments.length-1]._id);
You can manually generate the _id then you don't have to worry about pulling it back out later.
var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();
// then set the _id key manually in your object
_id: myId
// or
myObject[_id] = myId
// then you can use it wherever
_id field is generated at client side, you can get the id of the embedded document by comment.id
sample
> var CommentSchema = new Schema({
text:{type:String}
})
> var CommentSchema = new mongoose.Schema({
text:{type:String}
})
> var Story = db.model('story',StorySchema)
> var Comment = db.model('comment',CommentSchema)
> s= new Story({title:1111})
{ title: '1111', _id: 5093c6523f0446990e000003, comments: [] }
> c= new Comment({text:'hi'})
{ text: 'hi', _id: 5093c65e3f0446990e000004 }
> s.comments.push(c)
> s.save()
verify in mongo db shell
> db.stories.findOne()
{
"title" : "1111",
"_id" : ObjectId("5093c6523f0446990e000003"),
"comments" : [
{
"_id" : ObjectId("5093c65e3f0446990e000004"),
"text" : "hi"
}
],
"__v" : 0
}

inserting a new document in the arrray of documents

I want to add a new document to the following document having an outer key "User"
{
name:himani,
User:[
{
_id:e25ffgf627627,
Name:User1
},
{
_id:fri2i2jhjh9098,
Name:User2
}
]
};
Below is my code in which I am trying to add a new document to already existing document.
My code is:
var server = MongoServer.Create("mongodb://username:password#localhost:27017/?safe=true");
SafeMode mode = new SafeMode(true);
SafeModeResult result = new SafeModeResult();
var db = server.GetDatabase("himani");
var coll = db.GetCollection("test");
BsonDocument document = new BsonDocument();
document.Add("name", "himani");
result = coll.Insert(document, mode);
BsonDocument nested = new BsonDocument();
nested.Add("1", "heena").Add("2", "divya");
BsonArray a = new BsonArray();
a.Add(2);
a.Add(5);
nested.Add("values", a);
document["3"] = new BsonArray().Add(BsonValue.Create(nested));
coll.Save(document);
var query = Query.And(
Query.EQ("name", "himani"),
Query.EQ("3.1", "heena")
);
var match = coll.FindOne(query);
var update = Update.AddToSet("3", new BsonDocument {{ "count", "2" }});
coll.Update(query, update);
I want to add a new document to the User array. I am doing this by above code but its not working.Please tell me the right way of doing it.
I don't understand your document structure at all... and the only "user" array I could find in here was a field called "3". Your code does in fact work and appends a document into the "3" array. The below is the result after running your code. Perhaps you could be more clear as to what you want your document to look like after you have "appended" a user.
{
"_id":ObjectId("4fa7d965ce48f3216c52c6c7"),
"name":"himani",
"3":[
{
"1":"heena",
"2":"divya",
"values":[ 2, 5 ]
},
{
"count":"2"
}
]
}