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});
}
}
Related
I'm trying to get the list of posts for which the publish date is equal or less than the current date.
I'm using NestJS, Mongo & typeORM; which syntax should I use?
const posts =
await this.mbRepository.find(
{ where: { "deletedAt": null , "publishDate" <= currentDate } }
);
let firstPoint = new Date();
firstPoint.setHours(0);
firstPoint.setMinutes(0);
firstPoint.setSeconds(0);
let lastPoint = new Date();
lastPoint.setHours(23);
lastPoint.setMinutes(59);
lastPoint.setSeconds(59);
const posts = await this.mbRepository.find({ publishDate: { $gte: firstPoint, $lt: lastPoint } } });
Get current day and make two point. One as begining of the day and another as end of the day. Then you can use mongodb operator $gte and $lt. In this way you will get all post which have been publish in this time range.
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.
I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...
How can I set a default collection in a model schema in mongoose. Using the basic example, how can I have for example a default comment in the comments array. e.g.
var defaultComment = {title: 'add your first post'}
do I do something like this in the definition? comments: {type:[Comments], default:defaultComment }
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
mongoose.model('BlogPost', BlogPost);
According to the Mongoose documentation for Schemas, keys may specify a default value. So for your example, one might define the Comments schema as so:
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var CommentsModel = mongoose.model("comments", Comments);
Then, store your default comment, and use it as the default value in your BlogPost schema:
var defaultComment = new CommentsModel({
title: "Add your first post"
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : { type: [Comments], default: defaultComment }
, meta : {
votes : Number
, favs : Number
}
});
I hope this helps. Cheers!
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
}