How to do soft delete with mongodb using nodejs - node.js

I'm able to delete data from the view , but at the sametime its getting deleted from mongodb which shouldn't happen.
I tried mongoose-soft-delete plugin to perform soft delete, but it isn't working
//schema
var mongoose= require('mongoose');
let softDelete = require('mongoosejs-soft-delete');
var Schema=mongoose.Schema;
var newblogSchema=new Schema({
user_id:Number,
title:String,
description:String,
summary:String,
hashtag:String
})
var newblogs=mongoose.model('NewBlog',newblogSchema);
newblogSchema.plugin(softDelete);
module.exports=newblogs;
//html template
<table>
<tr>
<th>Title</th>
<th>Description</th>
<th>Summary</th>
<th>HashTags</th>
</tr>
<tr *ngFor="let blog of blogs;">
<td >{{blog.title}}</td>
<td [innerHtml]="blog.description| safeHtml">{{blog.description}}</td>
<td>{{blog.summary}}</td>
<td>{{blog.hashtag}}</td>
<td> <a routerLink="/blog"><button type="button"
(click)="editblog(blog._id,blog.title,blog.description,blog.summary,blog.hashtag)">
Edit</button></a>
<td><button type="button" (click)="deleteblog(blog._id)">Delete</button>
</tr>
</table>
//ts file
deleteblog(blogid) {
var result = confirm('Want to delete?');
if (result === true) {
this.blogservice.deleteblog(blogid).subscribe(response => {this.blogs = response; });
}
//service
deleteblog(blogid):Observable<any>{
return Observable.create(observer=>{
this.http.post('http://localhost:4000/api/deleteblog', {_id: blogid}, {headers: new HttpHeaders({'Content-Type':'application/json'})}
)
.subscribe((response:Response)=>{
observer.next(response);
observer.complete();
});
});
}
//api.js
router.post('/deleteblog',(req,res)=>{
var body=req.body;
newblog.findByIdAndRemove({_id:body._id},(error,newblog)=>{if(error){
console.log(error);
}
else{
return res.json({message:'deleted',data:newblog});
}
});
});
Now the data is getting deleted from view as well as mongodb.
Expected result is to delete data only from the view and not from mongodb

we can implement soft delete with plugin, middleware and $isDeleted document method
soft delete plugin code:
import mongoose from 'mongoose';
export type TWithSoftDeleted = {
isDeleted: boolean;
deletedAt: Date | null;
}
type TDocument = TWithSoftDeleted & mongoose.Document;
const softDeletePlugin = (schema: mongoose.Schema) => {
schema.add({
isDeleted: {
type: Boolean,
required: true,
default: false,
},
deletedAt: {
type: Date,
default: null,
},
});
const typesFindQueryMiddleware = [
'count',
'find',
'findOne',
'findOneAndDelete',
'findOneAndRemove',
'findOneAndUpdate',
'update',
'updateOne',
'updateMany',
];
const setDocumentIsDeleted = async (doc: TDocument) => {
doc.isDeleted = true;
doc.deletedAt = new Date();
doc.$isDeleted(true);
await doc.save();
};
const excludeInFindQueriesIsDeleted = async function (
this: mongoose.Query<TDocument>,
next: mongoose.HookNextFunction
) {
this.where({ isDeleted: false });
next();
};
const excludeInDeletedInAggregateMiddleware = async function (
this: mongoose.Aggregate<any>,
next: mongoose.HookNextFunction
) {
this.pipeline().unshift({ $match: { isDeleted: false } });
next();
};
schema.pre('remove', async function (
this: TDocument,
next: mongoose.HookNextFunction
) {
await setDocumentIsDeleted(this);
next();
});
typesFindQueryMiddleware.forEach((type) => {
schema.pre(type, excludeInFindQueriesIsDeleted);
});
schema.pre('aggregate', excludeInDeletedInAggregateMiddleware);
};
export {
softDeletePlugin,
};
you can use as global for all schemas
mongoose.plugin(softDeletePlugin);
or for concrete schema

For Soft delete, you should maintain an active flag column that should only contain values as 0 and 1.
This way, you could analyse whether a record is deleted or not.
While displaying, add another clause for displaying only the records that have flag value 1. And while deleting, just update that flag's value to 0.
This would do the job.
For Example, here user 2 is deleted. with activeFlag as 0.
ID memberID userStatus groupCode activeFlag
1 user1 1 4455 1
2 user2 1 4220 0
3 user3 2 4220 1

Try to use https://www.npmjs.com/package/soft-delete-mongoose-plugin
A simple and friendly soft delete plugin for mongoose.

Related

Is there any method to store array values in MongoDB's field?

I have a schema in which in one of the field i wanted it to store array of values. The schema is given below:
const memberSchema=new mongoose.Schema({
id:{
type:String,
unique:true
},
prefCurrency:{
type:String,
default:'AUD',
required:false
},
});
In the front end part, The user will select multiple currencies and which can be stored in the prefCurrency field of schema. The front end code is given below:
export default function MemberInformation() {
const { t } = useTranslation();
const[memberData,setMemberData]=useState([]);
const [member,setMember]=useState({id:"",prefCurrency:""})
var name,valueV;
const handleInputs=e=>{
console.log("Updated ",member)
name=e.target.name;
valueV=e.target.value;
setMember({...member,[name]:valueV})
}
const postData= ()=>{
setMemberData({...memberData,...member})
const {id,prefCurrency}=member;
var UpdatedMemInfo ={id,prefCurrency};
axios.put('/memberInfoUpdate', UpdatedMemInfo)
.then( res => {
alert('Updated successfully!');
}
)
.catch(err => {
console.log(err.response);
alert('An error occurred! Try submitting the form again.');
});
}
useEffect(() => {
async function fetchBooks() {
const response = await fetch('/memberinfo');
const json = await response.json();
setMemberData(json.memberLogin);
setMember(json.memberLogin);
console.log(json.memberLogin)
}
fetchBooks();
},[]);
return (
<Form.Select aria-label="Floating label select example" name="prefCurrency" value={member.prefCurrency} onChange={e=>handleInputs(e)}>
<span><ReactCountryFlag countryCode="AU" svg style={myStyle}/></span>
<option value="AUD" name="prefCurrency">AUD</option>
<option value="CAD" name="prefCurrency">CAD</option>
<option value="CHF" name="prefCurrency">CHF</option>
<option value="CNY" name="prefCurrency">CNY</option>
</Form.Select>
<Button variant="success" onClick={()=>postData()}>
Save Changes
</Button>
)
}
As in the above code, only one value can be selected and stored into the MongoDB but i want select multiple values and store in the form of array in the prefCurrency field of the schema and then retrieve it from the database to display it. What will be the code changes here?
The API for posting the above data in database is given below:
router.put('/memberInfoUpdate', async (req, res) => {
const {id,prefCurrency}=req.body;
var _id = req.body.id;
var UpdatedMemInfo = {
id:id,
prefCurrency:prefCurrency
};
Member.findOneAndUpdate(_id, UpdatedMemInfo, { new: true }, function(
err,
UpdatedMemInfo
) {
if (err) {
console.log("err", err);
res.status(500).send(err);
} else {
console.log("success");
res.send(UpdatedMemInfo);
}
});
});
The above update API is just for one value in the prefCurrency field but i want to have multiple selected values in it.
The prefCurrency Schema would look like this for storing array values.
const memberSchema=new mongoose.Schema({
id:{
type:String,
unique:true
},
prefCurrency:{
type:Array,
default:'AUD',
required:false
},
});
And the query for updating the prefCurrency is
var UpdatedMemInfo = {
id:id,
prefCurrency:[prefCurrency]
};
This will take array of values and update it.

CouchDB many-to-many fetching with dynamic sorting

I have a CouchDB index where documents are music files with fields artist, album, title, etc. I also want to store playlists of tracks and be able to fetch all of a playlist's tracks and optionally sort the results by arbitrary fields.
I've read through the documentation on joins and the blog post/comment example is basically the same architecture as my playlist/track one, so I already have the ability to fetch a playlist's tracks and sort them by some predetermined key.
Is there any way to combine a view (like in those docs) with post-hoc sorting by some other arbitrary field (artist, title, etc.)?
I don't mind using multiple queries, but collecting all of the returned document IDs and using them in a subsequent /_find query like {"_id": {"$in": [...]}} query is extremely slow. Sorting them client side is always an option, but then I'd need to implement sorting logic twice in my app: a server-side version for when I'm using /_find on all tracks and a client-side version for tracks returned from a playlist view.
(This would be trivially easy to accomplish with an RDBMS but my use case involves syncing data between mobile and desktop versions of the same app (which might be offline), which is what led me to CouchDB+PouchDB.)
This belongs in a comment but would be an ugly mess.
When not to use map/reduce is a must read blog post by Nolan Lawson. There the point made is to leverage document _id's as much as possible, and demonstrates that denormalization isn't always the answer.
I believe if you are able to refactor your id's and documents, it will be evident how a secondary index (or two!) will fill in the gaps.
I won't go further because it would be plagiarism - it can't be explained in simpler terms. Read that article, toy with this code.
const g_view_result = 'view_result';
const getAllArtists = async() => {
const options = {
include_docs: true,
startkey: 'artist_',
endkey: 'artist_\uffff'
};
allDocs(["name"], options);
}
const getAllAlbums = async() => {
const options = {
include_docs: true,
startkey: 'album_',
endkey: 'album_\uffff'
};
allDocs(["title"], options);
}
const getAllBowieAlbums = async() => {
const options = {
include_docs: true,
startkey: 'album_bowie_',
endkey: 'album_bowie_\uffff'
};
allDocs(["title"], options);
}
const allDocs = async(fields, options) => {
let html = [];
const results = getEl('results');
results.innerText = '';
let docs = await db.allDocs(options);
docs.rows.forEach(row => {
html.push(fields.map(f => row.doc[f]).join(", "));
})
results.innerText = html.join('\n');
}
// canned test documents
const getDocsToInstall = () => {
return [
/*---- artist ----*/
{
_id: 'artist_bowie',
type: 'artist',
name: 'David Bowie',
age: 67
},
{
_id: 'artist_dylan',
type: 'artist',
name: 'Bob Dylan',
age: 72
},
{
_id: 'artist_joni',
type: 'artist',
name: 'Joni Mitchell',
age: 70
},
/*---- albums ----*/
{
_id: 'album_bowie_1971_hunky_dory',
artist: 'artist_bowie',
title: 'Hunky Dory',
type: 'album',
year: 1971
},
{
_id: 'album_bowie_1972_ziggy_stardust',
artist: 'artist_bowie',
title: 'The Rise and Fall of Ziggy Stardust and the Spiders from Mars',
type: 'album',
year: 1972
},
{
_id: 'album_dylan_1964_times_they_are_changin',
artist: 'artist_dylan',
title: 'The Times They Are a-Changin\'',
type: 'album',
year: 1964
},
{
_id: 'album_dylan_1965_highway_61',
artist: 'artist_dylan',
title: 'Highway 61 Revisited',
type: 'album',
year: 1965
},
{
_id: 'album_dylan_1969_nashville_skyline',
artist: 'artist_dylan',
title: 'Nashville Skyline',
type: 'album',
year: 1969
},
{
_id: 'album_joni_1974_court_and_spark',
artist: 'artist_joni',
title: 'Court and Spark',
type: 'album',
year: 1974
}
]
}
//
// boilerplate code
//
let db;
// init example db instance
const initDb = async() => {
db = new PouchDB('test', {
adapter: 'memory'
});
await db.bulkDocs(getDocsToInstall());
}
initDb().then(() => {
document.querySelectorAll('.hide').forEach(el => el.classList.remove('hide'));
});
const getEl = id => document.getElementById(id);
.hide {
display: none
}
.label {
text-align: right;
margin-right: 1em;
}
.hints {
font-size: smaller;
}
<script src="https://cdn.jsdelivr.net/npm/pouchdb#7.1.1/dist/pouchdb.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<table id='actions' class='hide'>
<tr>
<td>
<button onclick='getAllArtists()'>All artists</button>
</td>
<td>
<button onclick='getAllAlbums()'>All albums</button>
</td>
<td>
<button onclick='getAllBowieAlbums()'>All albums by David Bowie</button>
</td>
</tr>
</table>
<div style='margin-top:2em'></div>
<pre id='results'></pre>

nested map() and find() do not work in express + mongoose but work in codesandbox

I got a route in express that get 2 different array of object from mongoDb and then return a new "contributions" array after i've added some data into it from "projectAll"
Here is one contributions object:
{
_id: "5f5b095f01ba8e40769f7301",
libId: "5f5a7a7701ba8e40769f72fb",
totalPaidAmount: 10000,
transactionId: "pi_1HQ4hVGmJhXXrXOXnr0pkXkv",
cart: [
{
_id: "5f5b095f01ba8e40769f7302",
amount: 5000,
projectId: "5f5b086601ba8e40769f72fe"
},
{
_id: "5f5b095f01ba8e40769f7303",
amount: 5000,
projectId: "5f5b08ae01ba8e40769f7300"
}
],
__v: 0
}
And one projectAll object:
{
projectCover: { id: "211290" },
title: "My title 2",
funded: 11000,
description: "Desc",
_id: "5f5b08ae01ba8e40769f7300",
libId: "5f5a7a7701ba8e40769f72fb",
__v: 0
}
I need to add projectAll.title and projectAll.projectCover into each contributions.cart objects.
To do so I match contribution.cart.projectId with projectAll._id.
router.get("/contributions/:id", async (req, res) => {
const id = req.params.id
try {
const contributions = await Contribution.find({id})
const projectAll = await Project.find({id})
const updatedContribution = contributions.map((contribution) => {
// Go through each cart of each contribution
const updatedCart = contribution.cart.map((cartItem) => {
// Find matching project
const matchingProject = projectAll.find((project) => {
// project OK =====> console.log(project)
// projectAll OK =====> console.log(projectAll)
// cartItem OK =====> console.log(cartItem)
return project._id === cartItem.projectId;
});
// Here return undefined =====> console.log(matchingProject)
const {projectCover, title} = matchingProject
return {...cartItem, projectCover, title
}
})
return { ...contribution, cart: updatedCart
}
})
res.send(updatedContribution)
} catch (err) {
res.status(500).send(err)
}
this code work perfectly in my codeSandBox : https://codesandbox.io/s/contribution-map-projects-vhv8z?file=/src/index.js
But in my express + mongoose environment I get undefined for matchingProject (i added comments in the code to show from where I get unwanted result)
Does anybody know why it doesn't work ?
Thanks a lot !
EDIT: console.log(typeof project._id, typeof cartItem.projectId) return object object
whereas in codesandbox those are strings.
Since they are both ObjectIds you can use mongoose equals() functions - so project._id.equals(cartItem.projectId). You cannot compare them, cause you'd compare their object reference. So either the above function will work or project._id.toString() === cartItem.projectId.toString()

Accessing child methods in parent for mongoose succeeds in array and fails with single child

UPDATE : Solution is at bottom of question
I have an express site using mongoose.
I'll greatly simplify to say that I have adults, kids, and house models. When I create methods on kids, I can call them from within methods on adults and get a result. I can also call them from my .ejs views. However, when I create methods on house, I can only get a result from my .ejs views and get undefined when called from within methods on adults. Example code follows.
adult.js
const mongoose = require('mongoose');
const adultSchema = mongoose.Schema({
name: { type: String },
size: {type: String},
kids: [{type: mongoose.Schema.Types.ObjectId, ref: 'Kid', required: true}]
house:{type: mongoose.Schema.Types.ObjectId, ref: 'House', required: true}
});
adultSchema.method({
getKidsDescription: function() {
if (this.kids.length < 1) {
return 'No kids yet';
} else {
let ev = 'Kids, aged: ';
let kds = this.kids;
kds.forEach(function(k){
ev = ev + 'k.getAge()' // works
})
return ev;
}
},
getHouseDescription: function(){
return 'A fabulous house on '+this.house.getFullStreet(); // does not work
}
})
module.exports = mongoose.model('Adult', adultSchema);
kid.js
const mongoose = require('mongoose');
const kidSchema = mongoose.Schema({
name: { type: String },
size: {type: String},
birthdate: {type:Date}
});
kidSchema.method({
getAge: function() {
return (Math.floor(new Date() - this.birthdate)/(1000*60*60*24*365))
},
})
module.exports = mongoose.model('Kid', kidSchema);
house.js
const mongoose = require('mongoose');
const houseSchema = mongoose.Schema({
name: { type: String },
city: {type: String},
street: {type:String}
});
houseSchema.method({
getFullStreet: function() {
return this.street + ' Road';
},
})
module.exports = mongoose.model('House', houseSchema);
When I make a query for theAdult, it looks like this:
controller.js
exports.main = async (req, res, next) => {
if (req.theAdult) {
try {
const found = await db.fetchAdult(req.theAdult._id)
res.render('/main', {
//theHouse: found.house //below I show this working
});
} catch(e) {
throw new Error(e.message)
}
} else {
res.redirect('/');
}
}
db.js
exports.fetchAdult = (id) => {
return Adult.findById(id)
.populate({ path: 'kids'})
.populate({ path: 'house'})
.exec()
.then(doc => {
return doc;
});
}
Assuming house is passed to view as an object when rendered (commented out above), this works
view.ejs
<p> <%= theHouse.getFullStreet() %></p>
Assuming house populated on the call to load the Adult, this returns undefined.
view.ejs
<p> <%= theAdult.house.getFullStreet() %></p>
At the same time, both of these work
view.ejs
<ul> <% theAdult.kids.forEach(function(k) { %>
<li><%= k.getAge() %> </li>
<% }); %>
</ul>
<p> <% theAdult.getKidsDescription() %> </p>
What I am not understanding is how the method calls work for objects in array and work in the view but do not work for objects on in an array. This is a single child error (for me). If it did not work in the view, I would assume that the method getFullStreet() was the problem, but it works in the view. If the array methods could not be called within the parent, I would assume the issue was with trying to access getFullStreet() in the parent.
What am I missing?
SOLUTION
I was fetching theAdult in my call to show view.ejs, but I was then actually relying on currentAdult which referred to req.adult and did not have the fields populated. My solution was to add a pre hook to the adult schema that always populates house on find.
in adult.js
adultSchema.pre('find', function() {
this.populate('house')
})
Have you tried passing a hydrated theAdult? It might only see the ObjectID, without any other data or methods.

How to query a single document from a Mongodb collection with react

I'm trying to build a search bar with a react frontend and node backend, that will let me search a customer ID from a mongoDB collection, then pull all of the data from a single document down from within the collection and display it on my react app.
Currently, I am just trying to get to get the single document bit to work, if this is possible. At the moment, it pulls down the entire collection.
My current Node code:
Search router
const express = require('express');
const app = express();
const tfiPaintCodesRouter = express.Router();
const PaintInfoSchema = require('../models/PaintInfoSchema.js');
tfiPaintCodesRouter.route('/get').get(function (req, res) {
const tfipaintcode = new PaintInfoSchema(req.body);
console.log(req.body)
tfipaintcode.save()
.then(tfipaintcode => {
res.json('Got data!!');
})
.catch(err => {
res.status(400).send("unable to get data");
console.log('CustomerID is required', err.res);
});
});
tfiPaintCodesRouter.route('/').get(function (req, res) {
PaintInfoSchema.find(function (err, tfipaintcodes){
if(err){
console.log('this is an error!', err.res);
}
else {
res.json(tfipaintcodes);
}
});
});
module.exports = tfiPaintCodesRouter;
Mongo schema using mongoose.
const mongoose = require('mongoose')
var uniqueValidator = require('mongoose-unique-validator');
const Schema = mongoose.Schema;
// Create schema
const PaintInfoSchema = new Schema({
customerID: {
required: true,
index: true,
unique: true,
type: String
},
companyName: {
index: true,
type: String
},
curtainCodes: {
index: true,
type: String
},
sinageCodes: {
index: true,
type: String
},
Notes: {
index: true,
type: String
},
Method: {
index: true,
type: String
},
},{
collection: 'tfiPaintCodes'
});
PaintInfoSchema.plugin(uniqueValidator);
module.exports = mongoose.model('PaintInfoSchema', PaintInfoSchema)
My current react code is:
import React from 'react';
import { Form, FormGroup, Input, Container, Row, Col } from 'reactstrap';
import './Search.css'
import axios from 'axios'
class Search extends React.Component {
constructor(props) {
super(props)
this.state = {
searchInfo: []
};
}
handleInputChange = (event) => {
event.preventDefault();
const { value } = event.target;
console.log('Value', value)
this.setState({
query: value
});
this.search(value);
};
search = query => {
axios.get('http://localhost:3001/getData')
.then(res =>{
const searchInfo = (res.data || []).map(obj => ({
company: obj.companyName,
sinage: obj.sinageCodes,
method: obj.Method,
notes: obj.Notes}));
this.setState({ searchInfo });
})
};
componentDidMount() {
this.search("");
}
render() {
return(
<Container>
<Form>
<Row>
<Col md={{ size: 6 ,offset: 3}}>
<FormGroup className="SearchBar">
<Input onChange={this.handleInputChange} type="search" name="search" id="exampleSearch" placeholder="search" />
</FormGroup>
</Col>
</Row>
</Form>
<ul>
{this.state.searchInfo.map(function(searchInfo, index){
return (
<div key={index}>
<h1>NAME: {searchInfo.company}</h1>
<p>{searchInfo.sinage}</p>
<p>{searchInfo.method}</p>
<p>{searchInfo.notes}</p>
</div>
)
}
)}
</ul>
</Container>
);
}
}
export default Search
The code above queries mongodb, then pulls down all of the data stored in my collection, here is an image of the returned data.
Data displayed in frontend
But i want to know if it is possible to just pull down one document in that collection, so it would just display one Name: and then the other 4 bits of data.
I have the data stored in Mlab, here is a screenshot of the documents stored in my collection.
data in mongodb
Is this possible? Thanks!
The best way is to pull only one document from the DB (if you don't need more in your case).
Mongoose, as any other ORM/ODM, gives you those options:
https://mongoosejs.com/docs/api.html#model_Model.findOne
With FindOne you can search for documents but get only one (aka. "the first found") document back.
If you need a fixed number of returned documents, you can use limit(10) to, for example, return only 10 documents.
Though it appears to me that your code-snippets don't show the exact segment where do the query in Mongoose, otherwise we could have shown you what to do in your own example.

Resources