简体   繁体   English

如何将MongooseMap转换为JSON对象以将其从Node js发送到React?

[英]How to convert MongooseMap to JSON object to send it from Node js to React?

In mongoose, there is Map data type that allows to store arbitrary keys. 在猫鼬中,有Map数据类型可以存储任意键。 I understand that to get and set values I should use get and set methods. 我知道要获取和设置值,我应该使用getset方法。 However, when I send an object to frontend, Nodejs sends just empty JSON object. 但是,当我向前端发送对象时,Nodejs仅发送空的JSON对象。 Is there a way to automatically convert Mongoose object, that has Map type, into JSON object to send over the network, without extracting every key with get on the backend? 有没有一种方法可以自动将具有Map类型的Mongoose对象转换为JSON对象以通过网络发送,而无需在后端使用get提取每个密钥?

My model: 我的模特:

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);

My controller: 我的控制器:

// '/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 didn't work; JSON.stringify无法正常工作; I checked database, it has the value. 我检查了数据库,它具有值。

There is nothing wrong with the .json() Syntax But with arguments of the .save() callback function .json()语法没有任何问题,但是带有.save()回调函数的参数

The save function's callback will accept the following arguments : save函数的回调将接受以下参数:

  • The error 错误
  • The document that was saved 保存的文档

Please read the mongoose Prototype.save() docs 请阅读猫鼬Prototype.save()文档

The link is here 链接在这里

Found the answer here . 这里找到答案。 The problem was in serialization. 问题出在序列化中。 To serialize an object that contains Map we can pass a function as the second argument to JSON.stringify as described in the link above. 要序列化包含Map的对象,我们可以将函数作为第二个参数传递给JSON.stringify ,如上面的链接所述。 Then we can deserialize on frontend by passing another function to JSON.parse . 然后,我们可以通过将另一个函数传递给JSON.parse来对前端进行反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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