[英]How to convert MongooseMap to JSON object to send it from Node js to React?
在貓鼬中,有Map數據類型可以存儲任意鍵。 我知道要獲取和設置值,我應該使用get
和set
方法。 但是,當我向前端發送對象時,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無法正常工作; 我檢查了數據庫,它具有值。
在這里找到答案。 問題出在序列化中。 要序列化包含Map的對象,我們可以將函數作為第二個參數傳遞給JSON.stringify
,如上面的鏈接所述。 然后,我們可以通過將另一個函數傳遞給JSON.parse
來對前端進行反序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.