findbyid and delete mongoose code example
Example 1: findbyid and delete mongoose await
Subscriber.findByIdAndRemove(subscriberId)
.then(() => {
res.locals.redirect = "/subscribers";
next();
})
.catch(error => {
console.log(`Error deleting subscriber by ID: ${error.message}`);
next();
});
Example 2: mongoose find by and delete
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
res.redirect("/campgrounds");
} else {
res.redirect("/campgrounds");
}
});
Example 3: mongoose model
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
Example 4: create document mongoose
var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });
small.save(function (err) {
if (err) return handleError(err);
// saved!
});
// or
Tank.create({ size: 'small' }, function (err, small) {
if (err) return handleError(err);
// saved!
});
// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {
});
Example 5: delete document mongoose
Tank.deleteOne({ size: 'large' }, function (err) {
if (err) return handleError(err);
// deleted at most one tank document
});
Example 6: mongoose modele
mongoose.connect('mongodb://localhost/gettingstarted', {useNewUrlParser: true,useUnifiedTopology: true});