0

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

4

2 回答 2

0

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

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

  • 错误
  • 保存的文档

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

链接在这里

于 2018-11-28T06:47:15.060 回答
0

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

于 2018-11-28T18:32:59.743 回答