已解决 – 客户端错误:消息中的坏对象:bson长度与我们find的不匹配

我正在将数据发布到利用Mongoose和MongoDB的Node / Express API上。 在尝试使用此模式进行批量插入时,数据和处理程序:

// Mongoose schema var NotificationSchema = new Schema({ uuid: { type: String, required: true, index: true }, message: { type: String, required: true }, url: { type: String, required: true } }); // sample data [ { 'uuid': '34e1ffef49ad4001bb9231c21bdb3be7', 'url': '/polls/4666386cb92348af93417e9abb9ce880/forecast/', 'message': '@btaylor has shared a poll with you' }, { 'uuid': '42d6a9f4b3f5416b952452c26e01789a', 'url': '/polls/4666386cb92348af93417e9abb9ce880/forecast/', 'message': '@btaylor has shared a poll with you' } ] // route handler Notification.prototype.bulkInsert = function(data, callback) { NotificationSchema.collection.insert(data, function(error, documents) { if (error) { return callback(error, null); } if (documents.length == 0) { return callback(null, null); } callback(null, documents); }); }; 

当通过Postman以x-www-form-urlencoded

 { [MongoError: Client Error: bad object in message: bson length doesn't match what we found] name: 'MongoError', err: 'Client Error: bad object in message: bson length doesn\'t match what we found', code: 10307, n: 0, connectionId: 125, ok: 1 } 

我的摩卡testing发布相同的数据工作得很好。 我究竟做错了什么?

[更新]

经过进一步的testing,看起来请求的主体在我的Django Web应用程序中使用请求库发布时,正在被不正确的分析。

我的post被构造为:

 requests.post(url, data=data) 

其中data是一个Python字典:

 {'data': [{'url': '/polls/4666386cb92348af93417e9abb9ce880/forecast/', 'message': '@btaylor has shared a poll with you', 'uuid': '34e1ffef49ad4001bb9231c21bdb3be7'}, {'url': '/polls/4666386cb92348af93417e9abb9ce880/forecast/', 'message': '@btaylor has shared a poll with you', 'uuid': '42d6a9f4b3f5416b952452c26e01789a'}]} 

上述路由处理程序接收的data参数从req.body.data填充。 在我的Express中间件中,我使用了以下主体parsing器:

 app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); 

但是,从Django /请求中发布的请求正文logging结果如下:

 [ 'url', 'message', 'uuid', 'url', 'message', 'uuid' ] 

为什么这些价值观被剥离出来,还有花括号来定义对象呢? 该post的内容types被正确报告为:

 application/x-www-form-urlencoded 

有人有主意吗? 顺便说一下,这是从邮差,完美。

原来在Python方面有一个问题,在Express方面有一个问题。

我从Python发布的对象列表需要在发布的值中设置之前转换为JSONstring:

 # views.py notifications = json.dumps([{"uuid": profile.uuid_str, "message": message, "url": poll_forecast_url} for profile in shared_with]) requests.post(url, data={'data': notifications}) 

在我的问题早些时候你会注意到,我表示邮差testing失败。 这是因为在Postman选项中设置了x-www-form-urlencoded的编码时,Express端的req.body.data的值被作为string接收。 为了解决这个问题,我在Notification.bulkInsert()函数调用之前添加了这一行:

 var data = typeof(req.body.data) == 'string' ? JSON.parse(req.body.data) : req.body.data; 

在将JSONstring传递给.bulkInsert()之前正确地将其转换为对象