I am new in mongodb with nodejs.I want to update the comments data.Here is my document
{
"__v": NumberInt(0),
"_id": ObjectId("565443b1172e19d51f98b0ed"),
"address": "tohana",
"comments": [
{
"_id": ObjectId("5654455fe088d89c20736e3c"),
"comment": "good man",
"uemail": "dinesh#gmail.com",
"uname": "dinesh"
},
{
"_id": ObjectId("565445e471dce6ca20705a84"),
"comment": "nice person",
"uemail": "kr#gmail.com",
"uname": "krishan"
},
{
"_id": ObjectId("5654460e7aa73bec2064060e"),
"comment": "bad person",
"uemail": "Rai",
"uname": "Rahul"
}
],
"email": "nishantg#ocodewire.com"▼,
"name": "Nishant"
}
I am using Angular js in frontend and nodeJs as backend. Here is my code:
app.post('/commentsSave/:id', function(req, res) {
var id = req.params.id; // userId
var input = JSON.parse(JSON.stringify(req.body)); //commentData
var commentId = input.id; //commentId
var name = input.name;
var email = input.email;
var comment = input.comment
res.send({data:id,data2:input});
})
app.post('/commentsSave/:id', function(req, res) {
var id = req.params.id; // userId
var input = JSON.parse(JSON.stringify(req.body)); //commentData
var commentId = input.id; //commentId
var name = input.name;
var email = input.email;
var comment = input.comment
Users.update({'comments._id': input.id},
{
$set: {
'comments.$.name': name,
'comments.$.email': email,
'comments.$.comment': comment
}
},function(error, result){
if(error){
console.log(error);
}
else{
console.log(result);
}
})
}
Related
Here i am using Nodejs application to get JSON response from external API.I need to capture few key-value pair of this response and need to save it MongoDB.
I am getting the response properly, but i am unable to save the data in database.
Requirement:
Each time i get this response from External server , i need to save it in table by rewriting any documents if already exists in this collection. Here i have nearly 7 array items in json response , i need to save corresponding key value pair from all of the items automatically .
Model:
var mongoose = require('mongoose');
const getAllUsersDataSchema = new mongoose.Schema({
userRefID:[] ,
userName:[],
divisionId: [{}],
divisionName:[{}],
emailId :[{}],
})
module.exports = getAllUsers = mongoose.model('getAllUsers',getAllUsersDataSchema );
**API Call where i am capturing external API response:**
const express = require('express');
const router = express.Router();
const request = require('request');
const config = require('../config');
const fs = require('fs');
const getAllUsers = require ('../db/getAllUsersListmodel');
var mongoose = require('mongoose');
mongoose.connect ('mongodb://localhost/testdb',{ useUnifiedTopology: true , useNewUrlParser: true });
router.get('/', (req, res) => {
// token in session -> get user data and send it back to the Angular app
var data =fs.readFileSync('../teamlist.txt', {encoding:'utf8'} )
console.log(data);
if (data) {
request(
{
method: 'GET',
url: 'https://api.mypurecloud.com/api/v2/users',
headers: {
'Authorization': 'Bearer ' + data
}
},
// callback
(error, response, body) => {
let userInfoResponse = JSON.parse(body);
res.send(userInfoResponse);
console.log(userInfoResponse.entities.length)
console.log(userInfoResponse.entities[0].division.id)
getAllUsers.create({
userRefID : userInfoResponse.entities.id,
userName: userInfoResponse.entities.name,
divisionId: userInfoResponse.entities.division.id,
divisionName:userInfoResponse.entities.division.name,
emailId:userInfoResponse.entities.primaryContactInfo.address
}, (error,post)=>{
console.log(error,post);
});
}
);
}
// no token -> send nothing
else {
res.send("Token Not Present - Kindly login in back");
}
//console.log(req.session.token);
});
Data is saving in DB but not getting any array data saved in to it.
{
"_id" : ObjectId("5fd998d61439a434983702cd"),
"userRefID" : [ ],
"userName" : [ ],
"__v" : 0
}
This is exact API JSON response i am trying to save it in DB and use it for future references:
{
"entities": [
{
"id": "07f426ff-506f-4e5e-afdb-2c7397edac61",
"name": "EPS Purecloud Support",
"division": {
"id": "36852a81-ad7f-4c71-a1cd-7f431c05179f",
"name": "",
"selfUri": "/api/v2/authorization/divisions/36852a81-ad7f-4c71-a1cd-7f431c05179f"
},
"chat": {
"jabberId": "5dcc25e1db8c7e19238a287d#cognizant3.orgspan.com"
},
"email": "eps#genesys.com",
"primaryContactInfo": [
{
"address": "eps#genesys.com",
"mediaType": "EMAIL",
"type": "PRIMARY"
}
],
"addresses": [],
"state": "active",
"username": "eps#genesys.com",
"version": 3,
"acdAutoAnswer": false,
"selfUri": "/api/v2/users/07f426ff-506f-4e5e-afdb-2c7397edac61"
},
{
"id": "c5ce06dc-6265-4d16-be18-f5fc5a918295",
"name": "Generic",
"division": {
"id": "36852a81-ad7f-4c71-a1cd-7f431c05179f",
"name": "",
"selfUri": "/api/v2/authorization/divisions/36852a81-ad7f-4c71-a1cd-7f431c05179f"
},
"chat": {
"jabberId": "5ebab3dba6686314f6913b98#cognizant3.orgspan.com"
},
"email": "integration-generic-a03293c0-945d-11ea-a64c-ebeb45b9d295#webhook.com",
"primaryContactInfo": [
{
"address": "integration-generic-a03293c0-945d-11ea-a64c-ebeb45b9d295#webhook.com",
"mediaType": "EMAIL",
"type": "PRIMARY"
}
],
"addresses": [],
"state": "active",
"username": "integration-generic-a03293c0-945d-11ea-a64c-ebeb45b9d295#webhook.com",
"version": 2,
"acdAutoAnswer": false,
"selfUri": "/api/v2/users/c5ce06dc-6265-4d16-be18-f5fc5a918295"
},
{
/** 3rd User *********/
}
{
/** 4th User *********/
}
],
"pageSize": 25,
"pageNumber": 1,
"total": 7,
"firstUri": "/api/v2/users?pageSize=25&pageNumber=1",
"selfUri": "/api/v2/users?pageSize=25&pageNumber=1",
"lastUri": "/api/v2/users?pageSize=25&pageNumber=1",
"pageCount": 1
}
Entities is an array of objects, but you are trying to refer to its properties as an object:
userRefID : userInfoResponse.entities.id, // but "entities": [ {"id":"...", "name":"..."} ],
userName: userInfoResponse.entities.name,
You have to collect the data in a loop, and only then insert it into the database:
const usersArray = userInfoResponse.entities.map(el => ({
userRefID : el.id,
userName: el.name,
divisionId: el.division.id,
divisionName: el.division.name,
emailId: el.primaryContactInfo[0].address
}));
getAllUsers.insertMany(usersArray)
Problem
Hi dev,
I have the problem that when I try to make a get request to the series by id it shows me null.
I have noticed from the Atlas Mongos platform that I created the collection but it does not show me the data, only the structure of the scheme shows me
Function.js
const fs = require('fs');
const fetch = require('node-fetch');
const BASE_URL = " http://localhost:8081/api/v1/"
async function getSeries() {
return new Promise((resolve , reject) =>{
setTimeout(() => {
const res = require('./simple_database/series/1.json' , 'utf8');
resolve(res)
}, 1000);
})
}
module.exports = {
getSeries
}
Router
The route allseries allows me to access all the content. What I want to do is pass that content to the SeriesModel, maybe it is there where I have the problem that the data is not being inserted correctly.
In the route series/:id is where the null value is returning to me
const express = require('express');
const router = express.Router();
const f = require('./function');
const SeriesModel = require('./models/series');
router.get('/allseries', (req, res) => {
f.getSeries().then((series) =>{
res.status(200).json({
series
})
}).then((doc) =>{
SeriesModel.insertMany(doc , function(err , docs){
if(err){
console.error(err)
}else{
console.log(docs);
console.info('%d serie were successfully stored.', docs.length);
}
})
})
});
router.get('/series/:id' , (req , res , next) =>{
const id = req.params.id;
SeriesModel.findById(id)
.exec()
.then((doc) =>{
console.log("From database " , doc);
res.status(200).json(doc)
}).catch((err) =>{
console.error(err);
res.status(500).json({error: err})
})
})
module.exports = router;
Model/series.js
const mongoose = require('mongoose');
const serieSchema = mongoose.Schema({
"_id": {
"$oid": {
"type": "ObjectId"
}
},
"series_id": {
"type": "String"
},
"aggregateRating": {
"reviewCount": {
"type": "Number"
},
"ratingCount": {
"type": "Number"
},
"#type": {
"type": "String"
},
"ratingValue": {
"type": "Number"
}
},
"episodes": {
"1x": {
"07 Ghost": {
"type": [
"Mixed"
]
}
}
},
"metadata": {
"description": {
"type": "String"
},
"url": {
"type": "String"
},
"image": {
"type": "String"
},
"type": {
"type": "String"
},
"id": {
"type": "String"
},
"name": {
"type": "String"
}
},
"1x": {
"07 Ghost": {
"type": [
"Mixed"
]
}
}
});
module.exports = mongoose.model("cr_series" , serieSchema);
It is because findById takes it's parameter in form of object like this
SeriesModel.findById({_id:id})
You need to tell your query to which json object you want to match your incoming object.
I have implemented the following code for pagination but I am unable to make it work. I need to complete it with the following json data:
following code is for Vt.js file
const express = require('express');
const app = express();
const cors = require('cors');
var MongoClient = require('mongodb').MongoClient;
app.use(cors())
var url = "mongodb://localhost:27017/";
var pagination = require('pagination');
var paginator = pagination.create('search', {
prelink: '/users',
current: 2,
rowsPerPage: 2,
totalResult: 10020
});
console.log(paginator.render());
app.get('/users', function(req, res) {
MongoClient.connect(url, function(err, db) {
if (err)
throw err;
var dbo = db.db("MyNewDatabase");
var data = dbo.collection("VirtualCapitalDB").find({}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
res.json(result);
db.close();
});
});
})
app.listen(8080, ()=>console.log('Listening on port 8080'));
once you access it without pagination you can get following json array
[{
"_id": "5bcb3c77dc56e939187c13a5",
"firstname": "dumindu",
"lastname": "nagasinghe",
"videocount": 5
}, {
"_id": "5bcb3ce6dc56e939187c13a9",
"firstname": "cha",
"lastname": "advv",
"videocount": 10
}, {
"_id": "5bcb3d4bdc56e939187c13ab",
"firstname": "dvvs",
"lastname": "scvssv",
"videocount": 4
}, {
"_id": "5bcb3d7adc56e939187c13ac",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb40f7a768f83918480a2b",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb4103a768f83918480a2c",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb4106a768f83918480a2d",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}, {
"_id": "5bcb4125a768f83918480a2e",
"firstname": "advav",
"lastname": "dvdvv",
"videocount": 5
}]
But I need to add pagination and get the 2 data objects for single page. How to implement that in code?
Best way to write pagination of array items
paginator(items, page, per_page) {
var page = page || 1,
per_page = per_page || 10,
offset = (page - 1) * per_page,
paginatedItems = items.slice(offset).slice(0, per_page),
total_pages = Math.ceil(items.length / per_page);
return {
page: page,
per_page: per_page,
pre_page: page - 1 ? page - 1 : null,
next_page: (total_pages > page) ? page + 1 : null,
total: items.length,
total_pages: total_pages,
data: paginatedItems
};
}
Try this module.
// Fetch all running lent loans
module.exports.fetchLends = function (req, res, next) {
var perPage = 5;
var page = req.body.page || 1; // req.body.page pass from client, which page required.
loans
.find({
lenderId: req.user._id,
_disbursed: true,
_approved: true,
_completed: false
})
.select(
"lenderId _disbursed _approved _completed userId disbursed_timestamp status principal lender_interest_amount emi_type completed_timestamp disbursed_timestamp emi.lender_interest_amount emi._disbursed emi._completed emi.principal emi.lender_interest_amount emi.status emi.due_date emi.extension_date_1 emi.extension_date_2 emi.extension_date_3"
)
.populate({
path: "userId",
select: "name"
})
.skip(perPage * page - perPage)
.limit(perPage)
.sort({
disbursed_timestamp: -1
})
.exec(function (err, loan) {
console.log(loan)
)}
}
You want to use the express-paginate module, it's better suited for this case. See the documentation on their github page.
The pagination module you are using needs to create a new http request to get the data, it's not what you need for your application.
I am trying to find and update a subdoc using mongoose and mongdb but I can't seem to find the subdocs using the ids.
My schema
var Attending = new Schema({
users: []
});
var Query = new Schema({
name: [],
url: [],
attending: [Attending],
img: []
});
Using the ids for both docs, just finding returns null for the doc. However, if i only using the general Id I can find the entire doc but not the subdoc.
Queries.findOne(
{ "_id": queryId, "attending._id": attendingId },
function(err, doc) {
if (err) throw err;
console.log(doc);
res.render('index');
}
);
sample doc
{
"_id": {
"$oid": "58d995026d7c8f0a3028a50f"
},
"img": [
"https://pic1",
"https://pic2"
],
"attending": [
{
"_id": {
"$oid": "58d995026d7c8f0a3028a505"
},
"users": [
"somebody"
]
},
{
"_id": {
"$oid": "58d995026d7c8f0a3028a506"
},
"users": [
"another person"
]
}
],
"url": [
"https://www.yelp.com/2",
"https://www.yelp.com/1"
],
"name": [
"The Rivermill",
"Sharkeys"
],
"__v": 0
}
I am using the correct ids and expect to the first subdoc in attending to be returned or whichever one is searched. Instead null is returned.
Queries is made like this:
var names = [];
var urls = [];
var imgUrls = [];
var attendingArray = [];
for (var i=0; i<10; i++) {
names.push(businesses[i].name);
urls.push(businesses[i].url);
imgUrls.push(businesses[i].image_url);
//add attending schema
var newAttending = Attending({
users: ["somebody"]
});
attendingArray.push(newAttending);
}
var newQuery = Queries({
name: names,
url: urls,
attending: attendingArray,
img: imgUrls
});
First of all I want to tell I have provided all the code required to understand and answer my question.
Now coming to point Please check that json file below and I will explain exact question there
Modelfile1: TaskInfo Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskInfo = mongoose.Schema({
isactive:{type:Boolean},
taskobject:{type:String},
taskdetails:{type:String},
iscompleted:{type:Boolean}
});
var TaskInfo = mongoose.model('TaskInfo', taskInfo);
module.exports.TaskInfo = TaskInfo;
module.exports.TaskInfoSchema = taskInfo;
Model file 2 Task Schema
var mongoose = require('mongoose');
var TaskInfoSchema = require("./taskinfo.js").TaskInfoSchema
var Schema = mongoose.Schema;
// Task schema
var taskSchema = mongoose.Schema({
tasktype : {type: String},
createdon : {type: Date, default: Date.now},
//createdby : {type: Schema.Types.ObjectId,ref: 'User'},
//visitedby : [{type: Schema.Types.ObjectId,ref: 'User'}],
taskinfo : [TaskInfoSchema]
});
module.exports = mongoose.model('Task', taskSchema);
Route file api.js:
var TaskInfo = require('../models/taskinfo.js').TaskInfo;
var Task = require('../models/task.js');
var config = require('../../config');
module.exports = function (app, express) {
var api = express.Router();
//GET method is for fetching all the tasks from the database,
api.get('/taskdb', function (req, res) {
//console.log("____");
Task.find({}, function (err, taskdb) {
if (err) {
res.send(err);
return;
}
res.json(taskdb);
});
});
//POST method is for saving all the tasks to the database,
api.post('/tasks', function (req, res) {
var task = {};
task.tasktype = req.body.tasktype;
task.taskinfo = [];
for (var i = 0; i < req.body.taskInfo.length; i++) {
console.log(i);
var taskInfo = new TaskInfo(req.body.taskInfo[i]);
task.taskinfo.push(taskInfo);
}
var taskObj = new Task(task);
taskObj.save(function (err) {
if (err) {
res.send(err);
return;
}
res.json({
message: 'Task has been created'
})
});
});
//middleware
api.use('/tasks/:taskId',function(req, res, next){
Task.findById(req.params.taskId, function(err, task){
if(err){
res.send(err);
return;
}
else if(task)
{
req.task = task;
next();
}
else
{
res.status(404).send ('no task found with such details');
}
});
});
!-- // PATCH METHOD --! want to partial update array fields
//patch method--- wrong implementation (google how to patch array fields)
api.patch ('/tasks/:taskId',function(req,res){
// if(req.body._id)
// delete req.body._id;
if(req.body.tasktype)
{
req.task.tasktype = req.body.tasktype;
}
req.task.save(function(err){
if(err){
res.send(err);
return;
}
res.json({message:'Task edited & updated '})
});
});
//put method
api.put ('/tasks/:taskId',function(req,res){
//var task = {};
req.task.tasktype = req.body.tasktype;
req.task.taskinfo = [];
for (var i = 0; i < req.body.taskInfo.length; i++) {
console.log(i);
var taskInfo = new TaskInfo(req.body.taskInfo[i]);
req.task.taskinfo.push(taskInfo);
}
req.task.save(function(err){
if(err){
res.send(err);
return;
}
res.json({message:'User info updated successfully'})
});
});
//put ends here
//Task deletion is working fine
api.delete ('/tasks/:taskId',function(req,res){
req.task.remove(function(err){
if(err){
res.send(err);
return;
}
res.json({message:'Task has been deleted'})
});
});
api.get('/tasks/:taskId',function(req, res){
res.json(req.task);
});
return api
}
Json file:
[
{
"_id": "55f7a31c83dc2aa80b549516",
"__v": 13,
"tasktype": "Extreme",
"taskinfo": [
{
"_id": "55f84a6e110db2bc0d5159a2",
"iscompleted": false,
"taskdetails": "This is task 1",
"taskobject": "paid",
"isactive": false
},
{
"_id": "55f84a6e110db2bc0d5159a3",
"iscompleted": false,
"taskdetails": "This is task 2",
"taskobject": "paid",
"isactive": false
},
{
"_id": "55f84a6e110db2bc0d5159a4",
"iscompleted": true,
"taskdetails": "This is task 3",
"taskobject": "paid",
"isactive": true
},
{
"_id": "55f84a6e110db2bc0d5159a5",
"iscompleted": false,
"taskdetails": "This is task 4",
"taskobject": "paid",
"isactive": false
}
],
"createdon": "2015-09-15T04:48:28.631Z"
}
]
Ok so you have taken a look at json file now suppose I want to delete 3rd array element from my document so that json look like :
[
{
"_id": "55f7a31c83dc2aa80b549516",
"__v": 13,
"tasktype": "Extreme",
"taskinfo": [
{
"_id": "55f84a6e110db2bc0d5159a2",
"iscompleted": false,
"taskdetails": "This is task 1",
"taskobject": "paid",
"isactive": false
},
{
"_id": "55f84a6e110db2bc0d5159a3",
"iscompleted": false,
"taskdetails": "This is task 2",
"taskobject": "paid",
"isactive": false
},
{
"_id": "55f84a6e110db2bc0d5159a5",
"iscompleted": false,
"taskdetails": "This is task 4",
"taskobject": "paid",
"isactive": false
}
],
"createdon": "2015-09-15T04:48:28.631Z"
}
]
When I try to find a subdocument using its id, it is returning me empty json file, but using parent document id they are accessible. I have referred mongodb docs and found that subdocument gets save that way.
Please tell me some method to delete particular array element.
Thank You