const updateTask = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.taskTitle) update.taskTitle = req.body.taskTitle;
if (req.body.taskContent) update.taskContent = req.body.taskContent;
if (req.body.role) update.role = req.body.role;
let task = await Task.updateOne(
{ taskId: id },
{
$set: {
update,
},
},
{ runValidators: true }
);
};
This is my code to update my data in database
as I am trying to update single single data or key if I want to update single data but it's not updating any thing i don't know where its not working as i tried to console data data come perfectly
const updateTask = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.taskTitle) update.taskTitle = req.body.taskTitle;
if (req.body.taskContent) update.taskContent = req.body.taskContent;
if (req.body.role) update.role = req.body.role;
let task = await Task.updateOne(
{ taskId: id },
{
$set: update,
},
{ runValidators: true }
);
};
all you have to do was remove curly brackets and it will work like a charm $set : update
what the variable Task is ? And I’m sorry, but I didn’t really understand your question, so could you rephrase it more clearly ?
If not, be careful, users might inject things into your database. You should use the mongo-sanitize script.
Like that :
And check if your id is in the right form. If in your database it is not in bjson with MongoId. If this is the case, do not hesitate to convert your id as realized below.
const sanitize = require('mongo-sanitize');
const mongo = require('mongodb');
const updateTask = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.taskTitle) update.taskTitle = sanitize(req.body.taskTitle);
if (req.body.taskContent) update.taskContent = sanitize(req.body.taskContent);
if (req.body.role) update.role = sanitize(req.body.role);
let task = await Task.updateOne(
{ taskId: mongo.ObjectId(sanitize(id)) }, // You can remove the mongo.ObjectId if your id is not a objectid.
{
$set: {
update,
},
},
{ runValidators: true }
);
};
Related
im a total newbie in js (typescript, mongoDB, node.)
i just found that my code is not behaving as i expected, im getting 6 registers on the mongoDB instead of just one, it should check if the register exists and then update it, i dont know if it is something related to the await / async or i am doing something wrong, thanks in advace, here is my code.
fields.forEach((value) => {
try {
const mongoConnection = new DocumentDbRepository();
let checksIfExists = await mongoConnection.getValue(key, information[uniqueValue]);
if(checksIfExists==null){
let insert = await mongoConnection.insertValue(information);
console.log(insert);
}
if(checksIfExists?.passValue===information.passValue){
console.log('---------update---------');
let sons = Object.values(information.ticketToRide);
information.ticketToRide = sons;
let update = await mongoConnection.updateRegister(information, checksIfExists._id);
console.log(update);
} else {
console.log('---------insert---------');
let sons = Object.values(information.ticketToRide);
information = sons;
let insert = await mongoConnection.insertValue(information);
console.log(insert);
}
} catch (error) {
console.log(error)
}
}
async getValue(uniqueValue: any, keyValue:any) {
if (this._connection == null) {
await this.connect();
}
const db = this._connection.db(DocumentDbRepository.DbName);
const ticketToRide = db.collection("ticketToRide");
const query = {};
query[uniqueValue] = ''+keyValue+'';
const passInfo = await ticketToRide.findOne(query);
return passInfo;
}
async insertValue(information: any) {
if (this._connection == null) {
await this.connect();
}
const db = this._connection.db(DocumentDbRepository.DbName);
const ticketToRide = db.collection("ticketToRide");
let check = await ticketToRide.insertOne(
information
)
return check;
}
First, you don't need to create a connection inside the loop.
Second, mongodb has an update() or updateMany() method that has a special option { upsert: true }. If it is passed, insert will happen automatically.
Usage example:
Person.update( { name: 'Ted' }, { name: 'Ted', age : 50 }, { upsert: true })
So I'm sending data properly to mongo and data (user input information), which is correctly held in backend. In console I'm getting interceptor that tells me that data is received from Mongo DB, but how to properly get those properties (user's email, title of photo and url blob) or 'data'? So it can be seen as individual data (email, title...) and not as the whole object like it can be seen in console now.
--THIS IS IN MY VUE--
dohvatiObjavu(){
this.objava = Objave.dohvati_objavu();
console.log("Current post " + this.objava);
}
},
-- THIS IS IN SERVICES--
[let Objave = {
async dohvati_objavu() {
let response = await Service.get(/galerija)
let data = response.data;
console.log("Current posts in services: "+data.naslov)
return {
id: data._id,
email: data.email,
naslov: data.naslov,
noviOpisSlike: data.noviOpisSlike,
slika: data.slikaReference,
}
},
}
--THIS IS IN BACKEND--
app.get ('/galerija', async (req , res) => {
let db = await connect();
let cursor = await db.collection('galerija').find();
let results = await cursor.toArray();
res.json(results);
});
-- MY CONSOLE--
Objave.dohvati_objavu(); is an async function. So you should also await this inside your Vue method dohvatiObjavu().
I created a simplified working example, based on your code:
const Objave = {
dohvati_objavu: async function() {
// mock Service.get(/galerija) with Promise.resolve
const data = await Promise.resolve({
id: 'mockId',
email: 'mockEmail',
naslov: 'mockNaslov',
noviOpisSlike: 'mockNoviOpisSlike',
slika: 'mockSlika',
});
return {
id: data._id,
email: data.email,
naslov: data.naslov,
noviOpisSlike: data.noviOpisSlike,
slika: data.slikaReference
}
}
}
const MyVueComponent = class {
objava = undefined;
// DOES NOT WORK
dohvatiObjavu() {
this.objava = Objave.dohvati_objavu();
console.log("[dohvatiObjavu] Current post ", this.objava);
}
// WORKS
async dohvatiObjavu2() {
this.objava = await Objave.dohvati_objavu(); // <!-- await
console.log("[dohvatiObjavu2] Current post ", this.objava);
}
}
const component = new MyVueComponent()
component.dohvatiObjavu();
component.dohvatiObjavu2();
I am using node.js, MySQL, knex, and express.
I am doing a simple query of a database, db.findAllEmoji().
const findAllEmoji = () => {
return knex('emoji')
.select('*');
};
I am working from previous code that works I am modeling after, but am still stuck. There are two large code blocks below The first is from my routes in which I render the page in routes\dashboard.js. The second is what I am modeling after.
What I have below in the first large code block returns undefined unless I use let query = await db.findAllEmoji();, only then will it return the results of the query. That would be fine, but...if I use await, then the .whereRaw and .orderBy throws these errors and I have not been able to get past these. Here's one of them.
TypeError: query.orderBy is not a function at C:\Users\pauli\repos\all-coursework-node-paulwinka\tests\02. MySQL database schema emoji\routes\dashboard.js:21:21 at processTicksAndRejections (internal/process/task_queues.js:97:5)
My sample code did not need await to work, so I would prefer a solution that figures out why my query doesn't work without await..or maybe.
So my questions are, why won't the original query not work without await...and how can I get it to work without await like in my model code?
And if I just must use await in this case, how can I fix the errors with orderBy not working?
I've only been using these for a few weeks and am still learning the ropes. Thanks. :)
const express = require('express');
const db = require('../db');
const debug = require('debug')('app:routes:dashboard');
// creating instance of router.
const router = express.Router();
router.use(express.urlencoded({ extended: false }));
router.use(express.json());
router.get('/', async (req, res, next) => {
try {
const search = req.query.search;
let query = db.findAllEmoji();
if (search) {
query = query.whereRaw('description LIKE ?', ['%' + search + '%']);
} else {
query = query.orderBy('emoji_id');
}
debug(`query length: ${query.length}`);
res.render('dashboard/dashboard-user', {
title: 'Dashboard - Emoji',
active: 'dashboard',
query,
});
} catch (err) {
next(err);
}
});
module.exports = router;
This is the code that did work that I am modeling after...maybe I am missed something obvious.
try {
const industry = req.query.industry;
const search = req.query.search;
const pageSize = parseInt(req.query.pageSize) || 10;
const pageNumber = parseInt(req.query.page) || 1;
const industryOptionList = {
selected: industry || '',
options: [
{ value: '', text: 'All Categories' },
{ value: 'hospitality', text: 'Hospitality' },
{ value: 'foodservice', text: 'Foodservice' },
{ value: 'IT', text: 'IT' },
{ value: 'defense', text: 'Defense' },
{ value: 'finance', text: 'Finance' },
{ value: 'construction', text: 'Construction' },
],
};
let query = db.getAllListings();
if (industry) {
query = query.where('company.industry', industry);
}
if (search) {
// query = query.whereRaw('MATCH (review.title, review.review_text) AGAINST (? IN NATURAL LANGUAGE MODE)', [search]);
query = query.whereRaw(
'listing_title LIKE ? OR company.industry LIKE ? OR company_name LIKE ? OR company_description LIKE ?',
['%' + search + '%', '%' + search + '%', '%' + search + '%', '%' + search + '%']
);
} else {
query = query.orderBy('posted_date');
}
const pager = await pagerUtils.getPager(query, pageSize, pageNumber, req.originalUrl);
const listings = await query.limit(pageSize).offset(pageSize * (pageNumber - 1));
debug(`listings length is ${listings.length}`);
if (!req.xhr) {
res.render('listing/listing-list', {
title: 'Jobify: Listings',
listings,
industry,
industryOptionList,
search,
pager,
});
} else {
res.render('listing/search-results', { listings, pager: pager, layout: null });
}
} catch (err) {
next(err);
}
});
Here is my ..db code too in case it helps.
// get connection config
const config = require('config');
const { sum } = require('lodash');
const databaseConfig = config.get('db');
const debug = require('debug')('app:server');
//connect to the database
const knex = require('knex')({
client: 'mysql',
connection: databaseConfig,
});
const findAllEmoji = () => {
return knex('emoji')
.select('*');
};
module.exports = {
knex,
findAllEmoji,
};
If you are not awaiting or calling .then() for query builder, the query gets only built, but it well never be executed.
Query builder works in a way that you can add more .where, .join etc. parts to the query in different lines of code (like you are doing in router.get('/', async (req, res, next) => {) and when the query is ready it needs to be executed so that it will only then sent to DB sever to get response.
how do I post to referenced schemas in mongodb while using async-await. i was able to create the get function but i am having a hard time creating the post and the put.
here is my get function :
I think, in your request body you should only pass issue id and user id. So when you get the task with your get task details API, mongoose will prepopulate the data.
Your request body should look like
{
issue: "5ca2b1f80c2e9a13fcd5b913",
user: "5ca2b1f80c2e9a13fcd5b90b",
record: {
votary: 80,
development: 90,
test: 100
},
date: "2019-03-01T15:00:00.000Z"
};
And then save the task details as
try {
const task = new TaskModel(req.body);
const result= await task.save()
return api.responseJSON(res, 200, result);
} catch (e)
{
// Error
}
Just wrap the code inside of post in a try/catch
export const post: Operation = async (req: express.Request, res: express.Response) => {
try {
const param: any = {};
const task = new TaskModel(req.body);
const newTask = await task.save()
return api.responseJSON(res, 200, newTask);
} catch(err) {
// treat error
}
}
You should not save the complete req.body instead save only those fields which your schema accepts. And according to Task schema issue and user fields should store id but not the complete object which is there in req.body. Please try this and update your post method accordingly:
export const post: Operation = async (req: express.Request, res: express.Response) => {
try {
let param: any = {};
const user = {
id: req.body.user.id
};
const issue = {
id: req.body.issue.id
};
param = req.body;
param.user = user.id
param.issue = issue.id
const task = new TaskModel(param);
const newTask = await task.save()
return api.responseJSON(res, 200, newTask);
} catch (e) {
api.responseJSON(res, 400, e)
}
};
I am trying to update a mongodb user document. It is as below
{
"_id":"123",
"email":"sam#example.com"
}
I want to add one field 'name' to this document.
My code is as below
async function test() {
const user = {"_id":"123", "email" : "sam#example.com" };
async function setUsername(user, update) {
await userCollection.updateOne(user, update);
}
await setUsername(user, { $set: { name: "sam"} });
}
test();
However, when I see in the db, I am not able to see the field set in the document.
I am sure I am missing someway how the node driver is implemented, but I am not sure of the issue.
I have even tried using upsert: true option which gave me an error as the document was already existing.
I guess I had given the function name wrong and I didn't create the document before.
posting the final snippet that works:
const { MongoClient } = require("mongodb");
async function test() {
const mclient = await MongoClient.connect("mongodb://localhost:27017/?w=1", {
useNewUrlParser: true
});
const db = mclient.db("test");
const userCollection = db.collection("user");
const user = { _id: "123", email: "sam#example.com" };
function setUsername(user, update) {
return userCollection.updateOne(user, update);
}
await setUsername(user, { $set: { name: "sam" } });
}
(async () => {
test();
})();