【问题标题】:How to convert MongooseMap to JSON object to send it from Node js to React?如何将 MongooseMap 转换为 JSON 对象以将其从 Node js 发送到 React?
【发布时间】:2019-04-30 00:03:05
【问题描述】:

在猫鼬中,Map data type 允许存储任意键。 我知道要获取和设置值,我应该使用 getset 方法。但是,当我向前端发送一个对象时,Nodejs 只发送空的 JSON 对象。 有没有办法自动将具有 Map 类型的 Mongoose 对象转换为 JSON 对象以通过网络发送,而无需在后端提取带有 get 的每个键?

我的模特:

var  mongoose = require('mongoose');

var User = require('./user');
var Post = require('./post');
const Schema = mongoose.Schema;
const ObjectId = mongoose.Schema.Types.ObjectId;

const DescriptionSchema = new Schema({
    timeStamp: {type: Date, default: Date.now},
    postid: {type: ObjectId, ref: 'Post'},
    userid: {type: ObjectId, ref: 'User'},
    dstrings:{
        type: Map,
        of: String// key value
      }
});

module.exports = mongoose.model('Description', DescriptionSchema);

我的控制器:

// '/v1/description/add'
    api.post('/add', authenticate,(req, res) => {
        let description = new Description({         
            postid: ObjectId(req.body.postid),
            userid: ObjectId(req.user.id), 
            dstrings:req.body.dstrings,

        });
        description.save(function(err, description) {
            if (err) {
                res.status(500).json({ message: err });
            } else {
//  description.dstrings is equal to {} on the frontend               
                    res.status(200).json( description );
                }
            });  
        });

JSON.stringify 不起作用;我检查了数据库,它具有价值。

【问题讨论】:

    标签: node.js json reactjs mongoose


    【解决方案1】:

    .json() 语法没有问题,但是 .save() 回调函数的参数

    保存函数的回调将接受以下参数:

    • 错误
    • 已保存的文档

    请阅读猫鼬 Prototype.save() 文档

    链接是here

    【讨论】:

    • 很高兴知道。我添加了参数,但它并没有解决问题。
    【解决方案2】:

    找到答案here。 问题在于序列化。要序列化包含 Map 的对象,我们可以将函数作为第二个参数传递给 JSON.stringify,如上面的链接中所述。然后我们可以通过将另一个函数传递给JSON.parse,在前端进行反序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2012-06-14
      • 2017-09-18
      • 2017-01-03
      • 2020-07-23
      相关资源
      最近更新 更多