How do I remove documents using Node.js Mongoose?
docs
is an array of documents. so it doesn't have a mongooseModel.remove()
method.
You can iterate and remove each document in the array separately.
Or - since it looks like you are finding the documents by a (probably) unique id - use findOne
instead of find
.
how to delete document from mongoose after certain time
For this to work you have to create the indexing on the field createdAt
first and then you have to create TTL indexes so that MongoDB can use to automatically remove documents from a collection after a certain amount of time.
db.collectionName.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 120 } )
You should check here for more details.
Or, Just try adding this to the schema, but this will just delete the documents in 2 minutes(This will help you understand if there is an issue with Conditional delete or not, follow the above link):
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Model = mongoose.model;
const UserSchema = new Schema(
{
email: {
type: String,
},
username: { type: String },
createdAt: {
type: Date,
default: Date.now,
expires: 120
},
points: {
type: Number,
default: 0,
},
validation: {
type: String,
},
isValidated: {
type: Boolean,
default: false,
},
roles: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Role",
},
],
password: {
type: String,
},
},
{ collection: "users" }
);
const User = Model("User", UserSchema);
module.exports = User;
Delete a key from a MongoDB document using Mongoose
In early versions, you would have needed to drop down the node-mongodb-native driver. Each model has a collection object that contains all the methods that node-mongodb-native offers. So you can do the action in question by this:
User.collection.update({_id: user._id}, {$unset: {field: 1 }});
Since version 2.0 you can do:
User.update({_id: user._id}, {$unset: {field: 1 }}, callback);
And since version 2.4, if you have an instance of a model already you can do:
doc.field = undefined;
doc.save(callback);
How to remove a field from all documents in a collection using Mongoose?
You can achieve the desired result like this:
first you have to add the 'code' field back to your Schema and then run the following code.
after that you can remove the code field from the Schema again.
const res = await Item.updateMany({}, {$unset: {"code": 1}});
res.n; // Number of documents matched
res.nModified; // Number of documents modified
or
Item.updateMany({}, {$unset: {"code": 1}}).then(res => {
console.log(res.n); // Number of documents matched
console.log(res.nModified); // // Number of documents modified
}).catch(err => console.log(err));
Mongoose: How to remove all documents with some field value
You can use deleteMany
to delete all documents that match the filters:
topicRoutes.route("/delete/:id").post(function(req, res) {
Topic.deleteMany({ user_id: req.params.id }, function (err) {});
});
Mongoose: How to trigger a function after a delete event is called using TTL
TTL deletions are handled by MongoDB. You could connect to a Change stream for that and listen for the deletes. But what about deletes that happen when your app does not run?
A more robust approach would be to store the urls to be deleted in a collection when the soft delete happens along with the date when to delete the images. A job checks this collection on a daily basis and purges the images.
A bit simpler yet more resource intensive would be to enumerate the images in a job on a daily basis and check whether there are still references in the venues collection. If not, the image can be removed.
How can I delete all objects over 24 hours old using Mongoose?
You have your signs a little mixed up.
You're saying greater than "right now", and less than 24 hours ago.
For simplicity, let's say "right now" is 86400
. That would make "24 hours ago" 0
.
So, you have: createdAt >= 86400 && createdAt <= 0
.
Well, that is impossible. No number can be greater than 86,400 and less than 0 at the same time.
You don't need to include the start date at all in this case. Ditch it and just have createdAt less than endDate and you should be good.
Related Topics
Meteor: Proper Use of Meteor.Wrapasync on Server
Nodemailer with Gmail and Nodejs
How to Automatically Reload a Page After a Given Period of Inactivity
Sorting Objects by Property Values
Clearrect Function Doesn't Clear the Canvas
How to Reset <Input Type = "File">
Reactjs Setstate() with a Dynamic Key Name
React.Js: Onchange Event for Contenteditable
Undefined Values in Array(Len) Initializer
How to Search JSON Tree with Jquery
Eslint Parsing Error: Unexpected Token
Generate Unique Number Within Range (0 - X), Keeping a History to Prevent Duplicates
Onclick Event Getting Called Automatically
JavaScript - Convert Array of Arrays into Array of Objects with Prefilled Values
Firestore: What's the Pattern for Adding New Data in Web V9