繁体   English   中英

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

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

在猫鼬中,有Map数据类型可以存储任意键。 我知道要获取和设置值,我应该使用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无法正常工作; 我检查了数据库,它具有值。

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

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

  • 错误
  • 保存的文档

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

链接在这里

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

暂无
暂无

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

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