当前位置:网站首页>Syntaxerror: unexpected token r in JSON at position 0

Syntaxerror: unexpected token r in JSON at position 0

2022-04-23 20:30:00 Different 213

The error message is :SyntaxError: Unexpected token R in JSON at position 0

This is my error code :

//  Query all article data 
    let articles = await Article.find().populate('author');

stay mongoose Use in populate Method to implement Collection Association , Cause template engine art-template Can't render , If used earlier JSON Data type conversion will report an error :SyntaxError: Unexpected token R in JSON at position 0

Solution one :populate After the method is called lean() Method .

This is the modified code :

//  Query all article data 
    let articles = await Article.find().populate('author').lean();

​ notes :lean() Method : Is to tell mongoose Returns a normal object , instead of mongoose Document object , I used it first JSON.stringify() This method converts the document object to a string , Remove all other attribute formats , Just leave the required data string !


Solution 2

// This document is : Blog foreground request processing file 
const {
     Article } = require('../../model/article');
//  Import paging module 
const pagination =  require('mongoose-sex-page');
module.exports = async (req, res) => {
    
    //  Query data from database 
    let result = await pagination(Article).page(1).size(4).display(5).find().populate('author').exec();

   
    let str = JSON.stringify(result);
    let json = JSON.parse(str);
    // res.send(json)
    //  Render the template and pass the data 
    res.render('home/default.art', {
    
        json
    });
}

Use stringify() Methods and parse() Method , Convert objects to strings , Then use it again parse() Method to JSON Format .
Be careful : When transferring data, the converted data is transferred json Variable .

版权声明
本文为[Different 213]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210550450972.html