【问题标题】:TypeError: Cannot create property '_id' on string '{"[object Object]":""}'TypeError:无法在字符串'{“[object Object]”:“”}'上创建属性'_id'
【发布时间】:2023-04-11 05:34:01
【问题描述】:

我正在尝试发布表单数据,但在提交时收到以下错误:

TypeError: 无法在字符串 '{"[object Object]":""}' 上创建属性 '_id'。

我的帖子被成功捕获:

电影{id: "8", firstname: "test", lastname: "test", hero: "test", photo: "xxxxxxxx"}

但是数据没有保存在 MongoDB 中。我正在使用 Angular2 的 MEAN 堆栈。

我的server.js

//Need to write the Express code

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var indexApi = require('./routes/index');
var movieApi = require('./routes/movie');

var port = 3000;

var app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// parse application/vnd.api+json as json
//app.use(bodyParser.json({ type: 'application/json' }))

app.use('/',indexApi);
// Register the movie.js file
app.use('/api',movieApi);

// View Engine
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);

// Set static folder so that our all the things we read from client folder
app.use(express.static(path.join(__dirname,'client')));

app.listen(port,function(){
  console.log("Server started at port number : "+ port);
});

我将数据发布如下:

 my app.component.ts:

 saveDetails(movieObj){
            //Note: I am getting the movie object here
            this.moviesService.saveMovie(movieObj).
                                            subscribe((data=> this.movieObj = JSON.stringify(data._body);
                                            console.log(this.movieObj);
                                             );

   }

  and movies.service.ts: 

    saveMovie(movie){
       //Note: I am getting the movie object here also
       var headers = new Headers();
       headers.append('Content-Type', 'application/x-www-form-urlencoded');
       return this.http.post('http://localhost:3000/api/movie',
                                        movie, {
                                        headers: headers});
    }

    movie.js:

    router.post('/movie',function(req,res){
        console.log("Under Post call....");
       var movieObj= req.body;

       // Note: here in the console everthing is comming as undefined thats is the problem
       console.log("[_id]"+movieObj._id+"[id]"+movieObj.id+"[firstname]"+movieObj.firstname+"[lastname]"+movieObj.lastname+"[hero]"+movieObj.hero+"[photo]"+movieObj.photo);

        db.movies.save(movieObj,function(err,docs){
            if(err){
            res.send(err);
             }
             res.json(docs);
       });
});

我得到的输出是 {"_id":"590aad3ec7133419f056bc77","\"{\\"[object Object]\\":\\"\\",\\"_id\\":\ \"590aa9c455f16d0eb440673e\\"}\"":""}]

点击http://localhost:3000/api/movies 网址时。

注意: 目的是在 MongoDB 中保存数据。

【问题讨论】:

    标签: node.js mongodb express mean-stack angular2-services


    【解决方案1】:

    MongoDB 接受 Object,而您传递的是 String

    错误

    var jsontest = JSON.stringify(movieObj); 
    

    正确

    var jsontest=movieObj;
    

    P.S : 假设 req.body 是正确的电影对象。

    【讨论】:

    • 我尝试了这个选项,但得到了相同的结果。一旦我点击 url:localhost:3000/api/movies 我得到 {"_id":"590aa9c455f16d0eb440673e","[object Object]":""}]。
    • @Prashant 那么前端正在发送这样的响应
    • 从前端点击提交。我得到了;电影 {id: "3", firstname: "cc", lastname: "zxc", hero: "xcz", photo: "xzc"} 这是正确的。
    • 我已根据您的 cmets 更新了文件。请看一下。我也提到了这个问题,我目前正在得到什么。谢谢
    • 那么应该是 req.body.Movie
    【解决方案2】:

    您已经在使用app.use(bodyParser.json());,它将消息的正文解析为一个 JavaScript 对象。你可以直接传递这个,省略

    var movieObj= req.body;
    var jsontest = JSON.stringify(movieObj);
    

    完全和刚刚拥有

    router.post('/movie',function(req,res){
        console.log("Under Post call....");
        db.movies.save(req.body, function(err,docs){ // req.body is js object, parsed by bodyParser
            if(err){
                res.send(err);
                return;
            }
            res.json(docs);
       });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 2022-01-25
      • 2013-06-10
      • 2019-07-20
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多