在 mongoose 中,有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 不起作用;我检查了数据库,它具有价值。