簡體   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