I'm trying to make a controller that will do something like this:
UPDATE bankapplication_accounts
SET last_successful_logged = last_present_logged
WHERE id = 1
My controller in sequelize looks like this:
exports.updateLastLoggedDate = (req, res) => {
User.findOne({
where: {
id: req.params.userId,
},
}).then(user => {
if (user) {
User.update(
{
last_successfull_logged: user.last_present_logged,
},
{ where: { id: req.params.userId } },
).then(() => {
res.status(200).send('logout correct');
});
}
});
};
Can this controller write better?
There are 2 ways
1:
exports.updateLastLoggedDate = (req, res) => {
User.findOne({
where: {
id: req.params.userId,
},
}).then((user) => {
if (user) {
user.update({
last_successfull_logged: user.last_present_logged,
}).then(() => {
res.status(200).send("logout correct");
});
}
});
};
2:
User.update(
{
last_successfull_logged: user.last_present_logged,
}, /* set attributes' value */
{
where: {
id: req.params.userId,
},
}, /* where criteria */
).then(() => {
res.status(200).send("logout correct");
});
Related
I am trying to update using this route.
router.put("/:id", async(req,res)=>{
try {
const updateUser = await User.findByIdAndUpdate(req.params.id, {
$push: {
clients:{
client_name: req.body.client_name,
client_Username: req.body.client_Username,
client_Password: req.body.client_Password,
documents : [
{
name : req.body.docName,
descritption : req.body.docDescription,
doc_upload : req.body.doc_upload,
}
]
}
}
},{new:true})
res.status(200).json(updateUser);
}
catch(err) {
res.status(500).json(err);
}
});
Once the function founds the id it updates client_name, client_Username and client_password without any issue.
My problem is when I try to update the nested array documents with a name/description and doc_upload. I am not able to do that.
What’s wrong ? How to do it please ?
One solution could be to separate the updates:
router.put('/:id', async (req, res) => {
try {
const { id } = req.params;
const { client_name, client_Username, client_Password } = req.body;
const updateUser = await User.findByIdAndUpdate(
id,
{
$push: {
clients: {
client_name,
client_Username,
client_Password,
},
},
},
{ new: true }
);
await User.findOneAndUpdate(
{
id,
'clients.client_name': client_name,
'clients.client_Username': client_Username,
},
{
$push: {
'clients.$.documents': {
name: req.body.docName,
descritption: req.body.docDescription,
doc_upload: req.body.doc_upload,
},
},
}
);
res.status(200).json(updateUser);
} catch (err) {
res.status(500).json(err);
}
});
I'm trying to update this attached
Mongo collection using the following controller, but getting bad value mongoError. Should I need to change the Model or are any changes needed in the current controller?
updateMarkCard = (req, res) => {
const reg = "66";
const sem = "sem-1";
const Ia = "IA-1";
MarksCardList.find({ student_id: reg }).exec((err, data) => {
if (err) res.status(400).json({ message: "Student Not Found" });
if (data) {
const findSem = data[0].marksCard_list.find((el) => {
return el.semister === sem;
});
const findIA =
findSem &&
findSem.IA.find((el) => {
return el.IA_type === Ia;
});
MarksCardList.findOneAndUpdate(
{
student_id: reg,
"marksCard_list._id": findSem._id,
},
{
$set: {
"marksCard_list.$[marksCard_list].IA.$[IA].marks": req.body.marks,
},
},
{
arrayFilters: [
{ "marksCard_list._id": findSem._id },
{ "IA._id": findIA._id },
],
}
).exec((er, data) => {
if (er) res.status(400).json({ ...er });
if (data) res.status(400).json({ data });
});
}
});
};
I want to search with my query getFoodType to return results based on whether the foodType of particular restaurant/takeaway is a "Chicken","Pizza" etc
Like this foodType: "Chicken"
I've tried using arguments and mongoDB filters (it's a MongoDB server) but no luck.
Schema
const EaterySchema = new Schema({
name: {
type: String,
required: true
},
address: {
type: String,
required: true
},
foodType: {
type: String,
required: true
}
});
My Schema Types
type Eatery {
id: String!
name: String!
address: String!
foodType: String!
}
type Query {
eatery(id: String!): Eatery
eateries: [Eatery]
getFoodType(foodType: String): [Eatery]
}
My Resolver
getFoodType: () => {
return new Promise((resolve, reject) => {
Eatery.find({})
.populate()
.exec((err, res) => {
err ? reject(err) : resolve(res);
});
});
},
Current Query in Apollo Playground
{
getFoodType (foodType: "Chicken") {
id
name
address
foodType
}
}
I essentially want to return all the results with "Chicken" as a the foodType. Something like foodType: "Chicken".
First, you need to get the value of the foodType to be queried in Resolver
const resolvers = {
Query: {
getFoodType: (_, args) => {
const { foodType } = args
...
},
},
}
Then use foodType when querying
Eatery.find({ foodType })
Finally need to return the result
new Promise((resolve, reject) => {
return Eatery.find({ foodType })
.populate()
.exec((err, res) => {
err ? reject(err) : resolve(res)
})
})
Complete example
const resolvers = {
Query: {
getFoodType: (_, args) => {
const { foodType } = args
return new Promise((resolve, reject) => {
return Eatery.find({ foodType })
.populate()
.exec((err, res) => {
err ? reject(err) : resolve(res)
})
})
},
},
}
Use the async/await
const resolvers = {
Query: {
getFoodType: async (_, { foodType }) => {
try {
const eaterys = await Eatery.find({ foodType }).populate()
return eaterys
} catch (e) {
// Handling errors
}
},
},
}
So i'm working in a mean stack application but i just don't get my api right..
The only thing that works is the GET !
My post and put doesn't seems to work, I think i got my syntax wrong but I just don't find the right one on the internet.
//GET
router.get('/employees', (req, res) => {
connection((db) => {
db.collection('employees')
.find()
.toArray()
.then((employees) => {
response.data = employees;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
// POST
router.post('/employees', (req, res) => {
const employees = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
db.collection('employees').insert(employees, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
//PUT
router.put('/employees/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const employee = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
db.collection('employees').update(details, employee, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(employee);
}
});
});
your PUT and POST methods dont have connections to the database established so db.collection is undefined in both
router.post('/employees', (req, res) => {
const employees = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
connection((db) => {
db.collection('employees').insert(employees, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
});
//PUT
router.put('/employees/:id', (req, res) => {
const id = req.params.id;
const details = { '_id': new ObjectID(id) };
const employee = { name: req.body.name, age: req.body.age , wage: req.body.wage , place: req.body.place };
connection((db) => {
db.collection('employees').update(details, employee, (err, result) => {
if (err) {
res.send({'error':'An error has occurred'});
} else {
res.send(employee);
}
});
});
});
I'm trying to do a push or pull based on a condition, along with an upsert
myCollection.update(
{'id': location},
{
$set: { count },
$setOnInsert: {
id: location,
users: []
},
},
{
$cond: {
if: (increment==1),
then: {$push: { users: userToken }},
else: {$pull: { users: userToken }}
}
},
{'upsert':true},
(err, data) => {
...
I'm trying to DRY this up (which works):
mongo.connect(dbUrl, (err, db) => {
if (err) throw err
let myCollection = db.collection('myCollection')
if(increment==1){
myCollection.update(
{'id': location},
{
$set: { count },
$push: { users: userToken },
$setOnInsert: {
id: location
}
},
{'upsert':true},
(err, data) => {
if (err) throw err
console.log(data);
callback()
db.close()
}
)
}
else{
myCollection.update(
...
$pull: { users: userToken },
...
)
}
})
It's not adding anything to the DB when I have $cond. Where should the $cond be?
$cond is not applicable here but in the aggregation framework. What you need is a pure old native JS conditional statement where you create the update document prior to using it in the update operation, and this of course should be set in a condition block. Consider the following example:
let queryObj = { 'id': location },
usersObj = { 'users': userToken },
updateObj = {
'$set': { count },
'$setOnInsert': queryObj
},
options = { 'upsert': true },
updateOperator = '$pull';
if (increment == 1) updateOperator = '$push';
updateObj[updateOperator] = usersObj;
myCollection.update(queryObj, updateObj, options,
(err, data) => {
if (err) throw err
console.log(data);
callback();
db.close();
}
)