简体   繁体   中英

TypeError: Converting circular structure to JSON for mongodb/mongoose

var express = require("express")
let PersonModel = require('./PersonModel')
let mongodbConnected=require('./MongodbConnect')
var app =express()
var bodyparser=require("body-parser")
const { format } = require("path")
const { count } = require("console")
const { countDocuments } = require("./PersonModel")
const { exec } = require("child_process")
const { get } = require("http")
const { ALL } = require("dns")
app.use(bodyparser.urlencoded({extended:false}))
app.get('/',function(req,res){
res.sendFile('Person.html', { root: __dirname });
})
app.get('/about',function (req,res){
res.send("This is a simple express application using mongodb express html and mongoose")
PersonModel.countDocuments().exec()
 .then(count=>{
 console.log("Total documents Count before addition :", count)
}) .catch(err => {
    console.error(err)
    })
   
   })
   app.post('/add', function(req,res){
    Pname=req.body.empname
    console.log('Pname',Pname)
    PAge=req.body.Age
    PGender=req.body.gender
    PSalary=req.body.salary
   
    const doc1 = new PersonModel(
    {
    name:Pname,age:33,Gender:PGender,Salary
   :PSalary}
    )
   
    doc1.save(function(err,doc){
    if (err) return console.error(err)
    else
    console.log("doc is added ",doc)
    //res.send("Record is added"+doc)
    res.send({
    'status':true,
    'Status_Code':200,
    'requested at': req.localtime,
    'requrl':req.url,
    'request Method':req.method,
    'RecordAdded':doc});

 }
 )
})
app.post('/findperson', function(req,res){

 PAge=req.body.Age
 console.log("Page",PAge)
 PersonModel.find({age:{$gte:PAge}})
 // find all users


 .sort({Salary: 1}) // sort ascending by firstName
 .select('name Salary age')// Name and salary only
 .limit(10) // limit to 10 items

 .exec() // execute the query
 .then(docs => {
 console.log("Retrieving records ",docs)
 res.send(docs)
 })
 .catch(err => {
    console.error(err)})


})
app.post('/delete', function(req,res){
Pgender=req.body.gender
PersonModel.findOneAndDelete({Gender:Pgender }
).exec()
.then(docs=>{
console.log("Deleted")
console.log(docs); // Success
}).catch(function(error){
console.log(error); // Failure
});
})
app.post('/update', function(req,res){
Pname=req.body.empname

Pnewname=req.body.newname
PnewAge=req.body.newage
PersonModel.findOneAndUpdate({ name: Pname },{"$set":{name:Pnewname,age:PnewAge}}).exec()
.then(docs=>{
console.log("Update for what i get is ",Pname
,Pnewname,PnewAge)
console.log(docs); // Success
}).catch(function(error){
    console.log(error); // Failure
 });
})

var docnum=PersonModel.countDocuments(ALL)
app.post('/count', function(req, res){
    res.send('Total number of documents: ', docnum)

})


app.listen(5000,function(){
console.log("Server is running on the port 5000")
})

Hello. First time posting on stackoverflow, dont know what kind of information to post, please let me know. Im trying to make a page (/count) to simply display the number of documents. I've tried different code but nothing is working. This error keeps coming up "TypeError: Converting circular structure to JSON".

This is school work so the code is given to me by a teacher and I have to add a POST method to add a page that displays total number of documents.

Any ideas? Thanks.

Circular structure is not about mongo but how JS read the JSON object.

For example, if you have this object:

var object = {
  propA: "propA",
  propB: object
}

When JS try to deserialize JSON object, will handle that: One object contains the object that contain again the object and again and again... that is a circular dependence.

Not only with one object itself, aslo with more objects:

var objectA = {
  propA: objectB
}
var objectB = {
  propA: objectA
}

Is the same case.

Using node.js you can use util.inspecet() which automatically show [Circular] when a circular dependence is found.

You can use like this:

var util = require('util')
console.log(util.inspect(objectA))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM