How to perform update in mongoose - node.js

I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks
My mongoose code,
exports.updatestudent = function (req, res) {
var student = new Student(req.body);
var data = {};
var id = req.params;
var params = req.body;
var item = {
'name': params.name,
'rollnumber': params.rollnumber,
'class': params.class,
'city': params.city
};
Student.update({ _id: id },{ $set: item }, function (err, result) {
if (err) {
console.log('err');
}
if (result) {
data = { status: 'success', error_code: 0, result: result, message: 'Article updated successfully' };
res.json(data);
}
});
};
my schema,
var StudentSchema = new Schema({
name: {
type: String
},
rollnumber: {
type: String
},
class: {
type: String
},
city: {
type: String
},
status: {
type: String
},
_id: {
type: Schema.ObjectId
}
});
/**
* Hook a pre validate method to test the local password
*/
mongoose.model('student', StudentSchema, 'student');
my result in postman,
{
"status": "success",
"error_code": 0,
"result": {
"ok": 0,
"n": 0,
"nModified": 0
},
"message": "Article updated successfully"
}
I am trying to update my record,but its not happening in my case and i am not sure about the case where it went rong,can any one suggest me help.Thanks

It seems you forgot to specify the key.
Replace
var id = req.params;
By
var id = req.params.id;

Make sure that you are getting your id in var id = req.params;
And I am sure you will not get your id like this
check your req.params; values and give your correct id in the query
Update
var item = {};
if (params.name) {
item.name = params.name;
}
if (params.rollnumber) {
item.rollnumber = params.rollnumber
}
Student.update({
_id: id
}, {
$set: item
}, function(err, result) {
if (err) {
console.log('err');
}
if (result) {
data = {
status: 'success',
error_code: 0,
result: result,
message: 'Article updated successfully'
};
res.json(data);
}
});

Related

how get dependent dropdown data in node with postgres

I have done following thing, using nodejs exoress with postgresql. For this api my input will be country id, modelname of country & for left join another model name im
{
"id": 1,
"module": "state_master",
"leftJoinmodule": "country_master"
}
exports.getStateDataByCountryId = async (req, res) => {
if (!req.body.module) {
return response.fail(res, "Model Name is Required", "");
}
const id = req.body.id;
var module = req.body.module;
var leftJoinmodule = req.body.leftJoinmodule;
console.log(leftJoinmodule)
if (Model[module]) {
Model[module]
.findAll({
raw: true,
where: {
country_id: id,
active: 1,
},
include: [{
model: Model.leftJoinmodule,
as: 'country'
},]
// include: [{
// model: Model.leftJoinmodule,
// as: 'country',
// where: {
// id: id
// }
// }]
})
.then((allStateMasterData) => {
return response.success(res, "All State Data", allStateMasterData);
})
.catch((err) => {
return response.catchError(res, err.message, "", module);
});
} else {
return response.fail(res, "Invalide Model Name", "");
}
};
getting below error
{
"status": 500,
"code": 0,
"message": "Include unexpected. Element has to be either a Model, an Association or an object.",
"data": ""
}
anyone plz help on this issue

Mongoose / Node : How to add an object to an array?

I have a problem when I try to update an array with Mongoose/Node.
I want to add my new price for example, req.body value is : { price: 12 } or req.body is : { description: 'my description' } but when I do this the total array is replace by just my new object ! :/
Here is my model:
const restaurantSchema = mongoose.Schema({
userId: { type: Object, required: true },
name: { type: String },
menus: [{
name: { type: String },
price: { type: String },
description: { type: String },
}],
})
And my node Js code :
const menuUpdate = req.body;
const menuId = req.params.menuId;
const userId = userIdFromToken(req);
const filter = {
userId: userId,
"menus._id": menuId
};
const update = { $set: { "menus.$": menuUpdate } };
const options = {
upsert: true,
new: true
};
Restaurant.findOneAndUpdate(filter, update, options).then(() => {
return res.status(204).json({ message: "Menus updated " });
});
Thanks for your help,
David
====
I change my code with the help of #aks, like this...
const menuUpdate = req.body;
for (const [key, value] of Object.entries(menuUpdate)) {
this.menuKey = `${key}`;
this.menuValue = `${value}`;
}
if (this.menuKey === 'name') {
this.update = { $set: { "menus.$.name": this.menuValue } };
}
if (this.menuKey === 'price') {
this.update = { $set: { "menus.$.price": this.menuValue } };
}
if (this.menuKey === 'description') {
this.update = { $set: { "menus.$.description": this.menuValue } };
}
const menuId = req.params.menuId;
const userId = userIdFromToken(req);
const filter = {
userId: userId,
'menus._id': menuId,
};
const options = {
upsert: true,
new: true
};
Restaurant
.findOneAndUpdate(
filter,
this.update,
options,
)
.then ( () => {
return res.status(204).json({ message: 'Menus updated ' });
});
Is there a way to simplify that without if ?
Your Node code
menus: [{
name: "toto",
price: 25,
description: "custom sweet",
}]
Now You have to update only the price from 25 to 45 for that you have to send the whole array.
So you have to simple set the array with this value
And if you go to other approach
then on req.body add one more parameter i.e menuIndex: 2
And on you update request make the condition if menuIndex is 2 then update specific column
const menuUpdate = req.body;
const menuId = req.params.menuId;
const userId = userIdFromToken(req);
const filter = {
userId: userId,
"menus._id": menuId
};
let update = {};
if (req.body.menuIndex === 1) {
update = { $set: { "menus.$.name": req,body.val} };
}
if (req.body.menuIndex === 2) {
update = { $set: { "menus.$.price": req,body.val
} };
}
if (req.body.menuIndex === 3) {
update = { $set: { "menus.$.description": req,body.val} };
}
const options = {
upsert: true,
new: true
};
Restaurant.findOneAndUpdate(filter, update, options).then(() => {
return res.status(204).json({ message: "Menus updated " });
});

Mongoose and Postman: test a model with nested objects

I created a model like this in nodeJS, using Mongoose:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var plantSchema = new Schema({
plantData: [
{
family: { type: String, default: 'Liliaceae' },
genusObj: {
genus: { type: String, required: 'Please enter the genus plant name' },
tulipGroup: { type: String }, // e.g. Single Early
tulipGroupNumber: { type: Number } // e.g. 1
},
species: { type: String, required: 'Please enter the species plant name' },
commonName: { type: String },
description: { type: String },
mainImage: {},
otherImages: {},
images: {},
}
],
detailsData: [ .... ]
});
module.exports = mongoose.model('plants', plantSchema);
And this is my controller:
var mongoose = require('mongoose'),
Plant = mongoose.model('plants');
// READ ALL
exports.list_all_plants = function(req, res) {
Plant.find({}, function(err, plants) {
if (err) {
res.send(err);
}
res.json(plants);
});
};
// CREATE
exports.create_new_plant = function(req, res) {
var new_plant = new Plant(req.body);
new_plant.save(function(err, plant_inserted) {
if (err) {
res.send(err);
}
res.json(plant_inserted);
});
};
// READ (probably plantId comes from an _id previously retrieved)
exports.read_a_plant = function(req, res) {
Plant.findById(req.params.plantId, function(err, plant_searched) {
if (err) {
res.send(err);
}
res.json(plant_searched);
});
};
// UPDATE
exports.update_a_plant = function(req, res) {
Plant.findOneAndUpdate(
{
_id: req.params.plantId
},
req.body,
{new: true},
function(err, plant_to_update) {
if (err) {
res.send(err);
}
res.json(plant_to_update);
}
);
};
// DELETE
exports.delete_a_plant = function(req, res) {
Task.remove(
{
_id: req.params.plantId
},
function(err, task) {
if (err) {
res.send(err);
}
res.json({ message: 'Plant successfully deleted' });
}
);
};
And finally, i have this router:
'use strict';
module.exports = function(app) {
var plantList = require('../controllers/plantController');
// plant routes
app.route('/plants')
.get(plantList.list_all_plants)
.post(plantList.create_new_plant);
app.route('/plants/:plantId')
.get(plantList.read_a_plant)
.put(plantList.update_a_plant)
.delete(plantList.delete_a_plant);
What I'd like to do is testing all this with Postman.
If I try with the GET method, using simply
http://localhost:3000/plants
everything works fine: I mean, it returns an empty array (mongodb is up and running, and everything is set).
Now I wanted to try to insert a new element with Postman: I selected POST and x-www-form-urlencoded under body. Required properties are plantData{genusObj{genus}} and plantData{species} : since I'm quite new with both postman and mongodb, how can I enter a sub-element in postman, to create a new Plant ?
there are only KEY and VALUE options, and i don't know how to write a sub-key like plantData->genusObj->genus.
P.S.: Suggestions on data model are welcome, I tried to build a generic plant database but oriented on tulips (so usually i can enter tulips, but if i need to enter something else, i can).
Well, it seems that this answer fits to me: in fact, on Postman i selected under "body" the "raw" option, then I selected JSON instead of TEXT from the dropdown menu, and finally I used this object (meanwhile I slightly changed the
model) - don't forget the " symbols everywhere, like I did - ' is not accepted:
{
"plantData": [
{
"family": "Liliaceae",
"genusObj": {
"genus": "Tulipa",
"tulipGroup": "Single Late",
"tulipGroupNumber": 5
},
"species": "TEST",
"sellName": "Queen of night",
"description": "black tulip",
"mainImage": "",
"otherImages": "",
"images": ""
}
],
"sellingData": [
{
"price": 0.50,
"availableQuantity": 100
}
],
"detailsData": [
{
"heightInCm": "60-65",
"floweringTime": "late spring",
"plantDepthCm": "20",
"plantSpacingCm": "10",
"bulbSizeInCm": "12",
"flowerColor": "Black",
"lightRequirements": "full sun"
}
]
}

Is there any way to rename the path while we select the complex object from mongodb using mongoose in nodejs?

I want to rename the path of the fields which are coming from the response.
My Query:
const allLeads = await Lead.find().select({
"basic.mobileNumber": 1
});
res.send({ allLeads });
Response I'm Getting
{
"allLeads": [
{
"_id": "5d9f0e2118d1a445bae077aa",
"basic": {
"mobileNumber": "1223654789"
}
},
{
"_id": "5d9f16a8cba7744902acb422",
"basic": {
"mobileNumber": "1123654789"
}
}
]
}
how I want the response
{
_id: 5d9f0e2118d1a445bae077aa,
mobileNumber: "1223654789"
},
{
_id: 5d9f16a8cba7744902acb422,
mobileNumber: "1123654789"
}
So is there any way yo archive this using mongoose?
I did it like this. Is there any other and better way to do this?
let simpleLeadInfo = [];
await SwatiLead.find()
.select({
_id: 1,
"basic.mobileNumber": 1,
})
.exec((err, data) => {
if (!err) {
for (lead in data) {
const obj = {
id: data[lead]._id,
mobileNumber: data[lead].basic.mobileNumber,
};
simpleLeadInfo = [...simpleLeadInfo, obj];
}
return res.send({ error: false, status: "OK", simpleLeadInfo });
}
});

elasticsearch search text return full array issue

I am using mongoosastic for elasticsearch. and i done all setup and its working fine. but problem is result are not getting properly.
FILE:- mongoose and mongoosastic.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var medicineSchema = require('./search')
var mongoosastic = require("mongoosastic");
var UserProfileSchema = new Schema({
userId: String,
username: String,
address: String,
number: Number,
task: [{
name: {
type: String,
es_boost: 2.0 // or es_indexed:true
},
taskCode: String,
}]
});
UserProfileSchema.plugin(mongoosastic);
UserProfileSchema.plugin(mongoosastic, {
host: "localhost",
port: 9200,
// ,curlDebug: true
});
UserProfile = module.exports = mongoose.model('UserProfile', UserProfileSchema);
UserProfile.createMapping(function(err, mapping) {
if (err) {
console.log('error creating mapping (you can safely ignore this)');
console.log(err);
} else {
console.log('mapping created!');
console.log(mapping);
}
});
And my search Query:
var UserProfileSchema = require('../../app/models/user');
UserProfileSchema.search({
query_string: {
query: name
}
}, function(err, result) {
if (err) {
callback({
RESULT_CODE: '-1',
MESSAGE: 'System error'
});
} else {
callback({
RESULT_CODE: '1',
DATA: result
});
}
});
Now my problem is if task array has 3 object and when i search for task string i.e "abc" it will return full collection. with all task But i want only searched string object from task array. i.e name :abc object
......
"task" [{
name: 'abc',
taskCode: 123
},{
name: 'xyz',
taskCode: 123
},{
name: 'cdx',
taskCode: 123
}]
The good thing is that your task field is already of type nested in your schema, which is a pre-condition for achieving what you expect.
Now in order to achieve what you want you need to use inner_hits in your query.
UserProfileSchema.search({
"query": {
"nested": {
"path": "task",
"query": {
"match": {
"task.name": name
}
},
"inner_hits": {} <--- this does the magic
}
}
}, ...

Resources