Cannot assign to read only property '_id' - node.js

get Error Cannot assign to read only property '_id' when insert data in mongodb using node js
Cannot assign to read only property '_id' of
{"Diagnosis":"vvvvv",
"Treatment":[{
"name":"treatment1",
"SubTreatment":[{
"name":"subtreatment1",
"SubTreatment2" : [{
"name":"subtreatmentexp1",
"$$hashKey":"object:27","Name":"vvvvv"
}],
"$$hashKey":"object:22","Name":"vvvvv"
}],
"$$hashKey":"object:12",
"Name":"vvvvv"
}
]}
please help me to solve this error
my code is
app.post('/post', function (req, res) {
var diagnosis;
var obj = req.headers['data'];
var temp = JSON.parse(obj)
console.log("Received body data:");
console.log(obj);
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
insertDocument(temp, db, function () {
db.close();
});
});
var insertDocument = function (obj, db, callback) {
try {
console.log(obj);
db.collection('diagnosis').remove();
db.collection('diagnosis').insertOne(obj, function (err, result) {
assert.equal(err, null);
console.log("Inserted a document into the Diagnosis collection.");
callback();
});
res.send("Inserted a document into the Diagnosis collection.");
} catch (err) {
console.log(err);
}
};
})
my function to call API is
$scope.post = function () {
var diagnosis = $scope.Treatments;
var httpRequest = $http({
method: 'POST',
url: '/post',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'data': JSON.stringify($scope.Treatments)
},
}).success(function (data, status) {
});
};
Treatments array....
$scope.Treatments =
{
Diagnosis: '',
Treatment: [
{
name: 'treatment1',
SubTreatment: [
{
name: 'subtreatment1',
SubTreatment2: [{ name: 'subtreatmentexp1' }]
}
],
}
]
};
Generated JSON to insert data is
{
"Diagnosis": "sss",
"Treatment": [
{
"name": "treatment1",
"SubTreatment": [
{
"name": "subtreatment1",
"SubTreatment2": [
{
"name": "subtreatmentexp1",
"$$hashKey": "object:27",
"Name": "sss"
}
],
"$$hashKey": "object:22",
"Name": "sss"
}
],
"$$hashKey": "object:12",
"Name": "sss"
}
]
}

Related

null response when calling lambda

My lambda function is returning a null response and I'm not sure why. When I change 'res.body' to 'res.statusCode' I get the status code 200 as expected. I've checked the logs of my api call and see that there are no issues with the details I am passing (also confirmed using a curl command. Any ideas?
const https = require('https');
function getRequest() {
const options = {
host: 'vehimgd36c3.execute-api.ap-southeast-2.amazonaws.com',
path: '/callinglink',
method: 'GET',
headers: {
'link': 'https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.Function.html'
}
}
return new Promise(function(resolve, reject) {
https.get(options, (res) => {
resolve(res.body)
}).on('error', (e) => {
reject(Error(e))
})
})
}
exports.GetReturnMessage = async (event) => {
try {
const result = await getRequest();
console.log(result)
return {
"sessionState": {
"dialogAction": {
"type": "Close"
},
"intent": {
"confirmationState": "Confirmed",
"name": "FinalResponse",
"state": "InProgress",
},
},
"messages": [
{
"contentType": "CustomPayload",
"content": result
},
]
};
} catch (error) {
console.log('Error is: ️', error);
return {
statusCode: 400,
body: error.message,
};
}
};
If you check how to use lambda and apigateway. apigateway expects the lamba function to return a response with the structure Read here
var response = {
"statusCode": 200,
"body": "{\n \"TotalCodeSize\": 104330022,\n \"FunctionCount\": 26\n}"
}
in that case you could try returning your object as follows:
exports.GetReturnMessage = async (event) => {
try {
const result = await getRequest();
console.log(result)
const response = {
"sessionState": {
"dialogAction": {
"type": "Close"
},
"intent": {
"confirmationState": "Confirmed",
"name": "FinalResponse",
"state": "InProgress",
},
},
"messages": [
{
"contentType": "CustomPayload",
"content": result
},
]
};
return {
"statusCode": 200,
"body": JSON.stringify(response)
}
} catch (error) {
console.log('Error is: ️', error);
return {
statusCode: 400,
body: error.message,
};
}
}

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 });
}
});

MongoSkin wrong insertion

I have an array with countries with the following structure:
{
"code": "ZW",
"name": "Zimbabwe",
"zipPattern": "[\\s\\S]*",
"states": [
{
"name": "Bulawayo"
},
{
"name": "Harare"
},
{
"name": "Manicaland"
},
{
"name": "Mashonaland Central"
},
{
"name": "Mashonaland East"
},
{
"name": "Mashonaland West"
},
{
"name": "Masvingo"
},
{
"name": "Matabeleland North"
},
{
"name": "Matabeleland South"
},
{
"name": "Midlands"
}
]
}
I am trying to insert them into MongoDb using MongoSkin with the following code
var countries = require('./mongo/ready/Countries');
db.collection('countries').find().toArray(function (err, result) {
if (result.length === 0) {
for (var i = 0; i < countries.length; i++) {
var obj = countries[i];
var states = obj.states;
db.collection('countries').insert({
name: obj.name,
code: obj.code,
zipPattern: obj.zipPattern
}, function (error, countryResult) {
var id = countryResult[0]._id;
for (var j = 0; j < states.length; j++) {
var state = states[j];
db.collection('states').insert({
countryId: id,
name: state.name
}, function (stateError, stateResult) {
if (stateError) console.log(stateError);
console.log(stateResult);
});
}
});
}
}
});
but the code inserts the states of the last country in the array (Zimbabwe) for each country in the array instead of the correct states. How can I fix it?
Generally we don't use async query(insert) between sync loop(simple for loop). Its give us abnoramal results. Node provides async loop to overcome this.
First of all require async module for this.
var async = require('async');
Now you can use following code for insertion of countries and their respective states
async.each(countries, function(obj, callback) {
var states = obj.states;
db.collection('countries').insert({
name: obj.name,
code: obj.code,
zipPattern: obj.zipPattern
}, function(error, countryResult) {
if (error) {
callback(error);
} else {
var id = countryResult[0]._id;
async.each(states, function(state, callback) {
db.collection('states').insert({
countryId: id,
name: state.name
}, function(stateError, stateResult) {
if (stateError) {
callback(stateError);
} else {
callback();
}
});
});
callback();
}
}); }, function(err) {
if (err) {
// handle error here
} else {
// do stuff on completion of insertion
} });
Thanks

MongoClient Native FindAndModify "Need update or remove" Error

My node.js client looks like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(mongoendpoint, function(err, db) {
if(err) throw err;
var collection = db.collection('test-collection');
var ws = new WebSocket(websocket_Endpoint);
ws.on('open', function() {
log.info('Connected.');
});
ws.on('message', function(data, flags) {
wsevent = JSON.parse(data);
var args = {
'query': {
id: '1.2.3.4'
},
'update': {
$set: {
lastseen: "201405231344"
},
$addToSet: {
record: "event123"
}
},
'new': true,
'upsert': true
};
collection.findAndModify(args, function(err, doc){
log.info(err);
});
});
});
When I run this, I get the following error:
info: name=MongoError, ok=0, errmsg=need remove or update
I can't figure out why. I can run the exact same args json above using RoboMongo and the query works just fine.
Robomongo Query
db['test-collection'].findAndModify({"query":{"id":"1.2.3.4"},"update":{"$setOnInsert":{"lastseen":"201405231344"},"$addToSet":{"record":"event123"}},"new":true,"upsert":true});
What am I missing?
Your args section is wrong, it should be an array and does not need key values for "query" and "update". And the "options" value also needs to be an object (sub-document):
var args = [
{ id: '1.2.3.4' },
{
$set: {
lastseen: "201405231344"
},
$addToSet: {
record: "event123"
}
},
{
'new': true,
'upsert': true
}
];
Or specifically in the call:
collection.findAndModify(
{ id: '1.2.3.4' },
{
$set: { lastseen: "201405231344" },
$addToSet: { record: "event123" }
},
{
'new': true,
'upsert': false
},
function(err, doc){
Examples are also included on the manual page.

Elastic search delete operation

Am new to elastic search and struggling to delete an entry from my collection.
I need a query similar to this one
DELETE FROM message WHERE id='1323'" and created_user = "user#gmail.com".
Following are my elastic search query, when i execute this, its only deleting the particular id field, its not taking the second argument created_user. Please help me to solve this issue. Thanks
var created = "9ed8afe738aa63c28b66994cef1f83c6"
db.delete({
index: 'outboxpro',
type: 'message',
id: req.body.post_id,
created_user: created
}, function (error, resp) {
if (error) {
return next(error);
}
var data = {};
console.log('delete response',resp);
if (resp.hits.successful < 1) {
data = {status: false, message: 'NO POST FOUND TO DELETE', code: 400};
res.send(data);
} else {
return next({status: true, message: 'POST DELETED', data: error, code: 500});
}
});
//// EDIT
I have tried deleteByQuery, following are my code
db.deleteByQuery({
index: 'outboxpro',
type: 'message',
body:{
"query": {
"filtered": {
"query": {
"match": {
"_id": {
"query": "Kal4AXi5R9G-IMx4GIKYMw"
}
}
},
"filter": {
"and": [
{
"term": {
"created_user": created
}
}
]
}
}
}
}
}, function (error, resp) {
if (error) {
return next(error);
}
console.log('post deleted');
});
You can delete documents matching your query, using delete by query in elasticsearch.. Refer
http://www.elasticsearch.org/guide/en/elasticsearch/client/javascript-api/current/api-reference-1-0.html#api-deletebyquery-1-0
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete-by-query.html
db.deleteByQuery({
index: 'outboxpro',
type: 'message',
body: {
"query": {
"filtered": {
"query": {
"match": {
"_id": "Kal4AXi5R9G-IMx4GIKYMw"
}
},
"filter": {
"term": {
"created_user": "created"
}
}
}
}
},
function (error, resp) {
if (error) {
return next(error);
}
console.log('post deleted');
});
The delete API will do exactly what you want, just in a slightly round-about way.
What you'll have to do first is search for the documents you want to delete, so construct a search query that find all documents with the id of '1323' and a created_user of 'user#gmail.com'. From the returned documents you'll be able to retreive the document ID which you then need to pass through to the delete API.
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-delete.html

Resources