使用Mongoose保存时的JSON格式未恢复预期结果

时间:2018-07-08 12:55:58

标签: mongodb express mongoose

我的Mongoose控制器中有一个代码块,试图同时找到“项目”和“级别”:

exports.landing = (req, res, next) =>  {
  console.log(req.params.projectid);
  Project.findById(req.params.projectid, (err, project) => {
    if (err) return res.status(500).send(err);
    //find the level based on the projectid
    Level.find({'projectid': req.params.projectid}, (err, level) => {
      if (err) return res.status(500).send(err);
      //find the level based on the projectid
      res.json({
        success: true,
        message: 'got',
        level: level.leveltempnodes
      });
      //res.render(path + 'project', {project: project, moment: moment, level: level});
    });
  });
};

在res.json部分中,如果我只使用“ level”而不使用点符号,则所有结果将按预期返回。当我尝试获取“ levelnodes”条目时,什么也没回来。与其他文档相比,我在关卡文档中唯一看到的不同之处是JSON结果包含一个[[::

{"success":true,"message":"got","level":{"_id":"5b4205ea5b44e146b5978175" ...

以上工作正常。但是我无法在以下结果上使用点语法:

{"success":true,"message":"got","level":[{"_id":"5b4202fc94855d56204c8bb7"

我正在这样保存关卡文件:

 var data = {
      levelname: levelname,
      leveltempnodes: leveltempnodes,
      projectid: projectid};


      var level = new Level(data);
      level.save(function (err) {
        if (err) return handleError(err);
      })

我的错误是什么都没有回来:

{"success":true,"message":"got"}

模式:

const mongoose = require('mongoose');

const LevelSchema = mongoose.Schema({
    levelname: String,
    leveltempnodes: String,
    projectid: String
});

module.exports = mongoose.model('Level', LevelSchema);

数据被毫无问题地存储在数据库中。我通过Ajax添加它:

   var p = {
      projectname : $("#projectname").val(),
      levelname : 'Root',
      leveltempnodes : '{"class":"go.GraphLinksModel","nodeKeyProperty":"id","nodeDataArray":[{"id":1,"loc":"226 226","text":"sensor"},{"text":"perception","loc":"426 225.99999999999997","id":-2},{"text":"planning","loc":"626 225.99999999999997","id":-3},{"text":"gate","loc":"826 225.99999999999997","id":-4}],"linkDataArray":[{"from":1,"to":-2,"text":"msg","points":[296.7874157629703,237.73538061447854,340.03133208792605,227.76937481449303,383.33478829426565,227.0952320784595,426.7981545990892,236.1401244399739]},{"from":-2,"to":-3,"text":"msg","points":[523.225709890083,236.1861908341044,558.0349502392196,229.00680324793404,592.1479459982006,228.54232080927673,626.6289592123036,236.76409981273324]},{"from":-3,"to":-4,"text":"msg","points":[709.6483081744094,237.23795381070627,748.7663709980919,229.48139598538538,787.383185499046,229.48139598538538,826.1210439041331,238.64104211943584]}]}',
    }

    if(p.projectname == ''){
      console.log('e');
    }else{
      $.ajax({
        type: 'POST',
        contentType : "application/json",
        url: 'api/project/save',
        data : JSON.stringify(p),
        success: function(res) {
          window.location.replace("/project/"+res.id);
        }
      });

0 个答案:

没有答案