Elasticsearch sync/update after MongoDB document update with Mongoosastic - javascript

I am using MongoDB, Mongoose, Elasticsearch and Mongoosastic on a Node project. I have a MongoDB Atlas database and a local Elasticsearch database which are mapped together. When I create a new Document in MongoDB it is created in ES as well, and when I delete it in Mongo it is deleted in ES too. So everything works until this point.
What I did next is, I added an update route to update specific documents in Mongo. They do get updated but the changes are not reflected in ES because I might be missing something. Does anyone have any ideas?
Here is the Model/Schema in donation.js:
const mongoose = require('mongoose');
const mongoosastic = require('mongoosastic');
const Schema = mongoose.Schema;
const donationSchema = new Schema({
donorUsername: {
type: String,
required: true,
es_indexed:true
},
bankName: {
type: String,
required: true,
es_indexed:true
},
qualityChecked: {
type: String,
required: true,
es_indexed:true
},
usedStatus: {
type: String,
required: true,
es_indexed:true
},
}, { timestamps: true });
donationSchema.plugin(mongoosastic, {
"host": "localhost",
"port": 9200
});
const Donation = mongoose.model('Donation', donationSchema , 'donations');
Donation.createMapping((err, mapping) => {
console.log('mapping created');
});
module.exports = Donation;
Here are the create and update functions/routes in donationController.js:
const donation_create_post = (req, res) => {
console.log(req.body);
const donation = new Donation(req.body);
donation.save()
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
const donation_update = (req, res) => {
const filter = { donorUsername: req.body.donorUsername };
const update = { bankName: req.body.bloodbankName,
qualityChecked: req.body.qualityChecked,
usedStatus: req.body.usedStatus };
Donation.findOneAndUpdate(filter, update)
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}

Solved it. Added {new: true} in Donation.findOneAndUpdate(filter, update, {new: true}).

Related

Show 404 when endpoint exists mongoDB

I keep getting a 404 when I am posting to a route. I am using MongoDB, express and React Native. I have created the Schema, actions and router.
The Schema is below:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Edible Schema
const EdiblesSchema = new Schema({
name: {
type: String,
required: true
},
price: {
type: String,
required: true
},
strength: {
type: String,
required: true
},
purchasedLocation: {
type: String,
required: true
},
effects: {
type: String,
required: true
},
strain: {
type: String,
required: true
},
});
module.exports = Edibles = mongoose.model("edibles", EdiblesSchema);
Then the post router is below:
const express = require("express");
const router = express.Router();
const keys = require("../../config/keys");
// Load edibles model
const Edibles = require("../../models/edibles");
// #route POST api/users/edibles
// #desc Add an edible to the users collection
// #access Public
router.post ('/edibles', (req, res) => {
if (res.status === 200) {
const newEdible = new Edibles({
name: req.body.name,
price: req.body.price,
strength: req.body.strength,
strain: req.body.strain,
purchasedLocation: req.body.purchasedLocation,
effects: req.body.effects,
})
} else {
return res.status(400).json({ email: "Thats not going to get you high" });
} newEdible
.save()
.then( edibles => res.json(edibles))
.catch(err => console.log(err))
});
module.exports = router;
Then the finale we have the handleSubmit to send the users info to the api endpoint.
const handleSubmit = (response) => {
console.log("EDIBLES", name, strength, price, effects, strain)
dispatch(setEdible(payload))
if (response === 200) {
axios
.post(edibleApi, payload)
console.log("PAYLOAD", edibleApi, payload, setEdible)
// navigation.navigate("Dashboard")
} else {
console.log("WRONG", edibleApi, payload, setEdible);
console.log("userEdibles", userEdibles)
}
}
I am really lost with this... Please help!
The issue was that I was using the wrong endpoint. I worked this out by using the express-list-routes by adding it to my server.js file.
const expressListRoutes = require('express-list-routes');
const router = express.Router();
console.log("Now we cooking with gas", expressListRoutes(app, { prefix: '/api/v1' })))
That console.log must be added to the console.log that indicates if your server is running or not....

How can I start NodeJS post?

I am trying to create a sample API of restaurants using POST but after starting API and loading it into Postman it does not show results.
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sample',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
restaurant.js (Controller)
const restaurants = require('../Models/restaurantData');
exports.getfilter = (req, res) => {
const city_name = req.body.city_name;
const cost = req.body.cost;
restaurants.find({
city_name: city_name,
cost: cost
}).then(result => {
res.status(200).json({
message: "Filtered Data",
result
})
}).catch(error => {
res.status(500).json({
message: error
})
})
}
restaurantData.js (Model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
I think mostly it is the router problem but trying to know where? So, share any ideas. Thank You.
This request handler:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
Does not actually call the getfilter function so nothing is ever sent from the POST request. You can fix that by either doing this:
router.post('/restaurantFilter', restaurantController.getfilter);
or this:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter(req, res);
});
Then, it looks like you also have to property export and import that getfilter() function. You appear to export it just fine in restaurant.js:
exports.getfilter = (req, res) => { ... });
But, you don't seem to be importing the controller properly as you're doing this:
const restaurantController = require('../Controllers/restaurantData');
When it looks like you should be doing this:
const restaurantController = require('../Controllers/restaurant.js');
so that you're assigning the controller the object that actually has the getfilter method on it.

Mongoose are returning undefined value of property

Well, I'm trying to get a value of property from a object with Mongoose find(), but for some reason, the mongoose are returning a undefined value.
The Schema:
const mongoose = require('mongoose');
const uuid = require('uuid');
const Schema = mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", Schema);
module.exports = Members;
The code
// Database connection
mongoose.connect(DATABASE.uri, DATABASE.options);
Members.find({ 'dsID': dsID }, (err, member) => {
const connected = member.mcConnected;
console.log(connected)
});
This might be because of you should not name a model 'Schema'. Try with other name because "Schema" is reserved word
Use this code on schema
const mongoose = require('mongoose');
const uuid = require('uuid');
const memberSchema = new mongoose.Schema({
dsID: { type: String, unique: true, require: true },
dsTag: { type: String },
mcCode: { type: String, default: () => uuid.v4(), unique: true, select: false },
mcConnected: { type: Boolean, default: false }
}, { versionKey: false });
const Members = mongoose.model("Members", memberSchema);
module.exports = Members;
Here u go boys:
const app = express()
const port = 3000
//MongoDB Connection
const DB_Connect = require('./(8.1)MongoDB_Connection')
const DB = DB_Connect() //returning a Model
//Middleware
const logger = function(req, res, next) {
console.log('logging')
next()
}
app.use(logger)
//Routes
app.get('/', async(req, res) => {
console.log(DB.then((docs) => {
console.log(docs.find({ name: 'POCO X3 Pro' }, (error, docs) => {
if (error) {
console.log("Error: " + error)
} else {
console.log(docs)
}
}))
}))
})
/*
DB is a Model and console.log(DB) gives : " Promise { Model { users } } ".
But for Promise we use .then() for result.
Model { users }
As we use .find(), we got the answer
*/
//Listening
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
//Muhammad Irtaza Ghaffar (Pakistan)
Thanks me later!

is there a method to execute a function after a spesific condition in express js

for exemple I have a user model like this
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
username: {
type: String,
required: true,
},
Points: {
type: Number,
default: 0,
},
module.exports = User = mongoose.model("users", UserSchema);
then I want to execute a function automatically when user.points is equal to 10 with express js, is there any solution ?
#Yessine, may you should try something like this. You can add checkForPoints wherever you are updating the Points and proceed with your things,
const { Users } = require('/schema.js');
const checkForPoints = async (username) => {
await Users.findOne({ username }, function (err, data) {
if (err) {
console.log("enter error ------", err)
}
if (data && data.Points === 10) {
// Execute your code
}
});
};
// Users schema(schema.js)
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('your db', { useNewUrlParser: true });
const requestSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId,
username: String,
Points: Number
});
module.exports = mongoose.model('users', requestSchema);
Polling is a technique where we check for fresh data over a given interval by periodically making API requests to a server.enables you to periodically check for the newest values of data and do further requests once it enters the desired state.

Fail to load custom mongoose schema in another js file

I've this project folder structure:
And I'm trying to import my user schema in my user ctrl but when i start nodemon users.ctrl.js gives me this error:
const {Users} = require('users.schema');
^
SyntaxError: Unexpected token
This is the user schema:
const mongoose = require('mongoose');
const validator = require('validator');
// {
// email: 'andrew#example.com',
// password: 'adpsofijasdfmpoijwerew',
// tokens: [{
// access: 'auth',
// token: 'poijasdpfoimasdpfjiweproijwer'
// }]
// }
var Users = mongoose.model('Users', {
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}
},
password: {
type: String,
required: true,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
module.exports = {Users}
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
And this is the user ctrl:
const mongoose = require('mongoose');
const {Users} = require('users.schema');
getAll = (req, res) => {
// let id = req.params.userId;
console.log('GET all cards');
Users
.find()
.select('users')
.exec((err, doc) => {
console.log('Risultato: ', doc);
});
};
module.exports = {
getAll
};
Where am I wrong? Is there something that escapes me?
By default node corresponds to /node_modules where the node packages are stored. Hence use relative path names to access the file require(./filename).
I solved the problem:
On this current pc that i'm using i had node version number 5.0.7 . To use the new ecma6 features i need to install v 8.0....
After installing the version I solved the problemAfter installing the version I solved the problem

Categories