node.js - 在express api中返回时,mongoose中_id的类型错误

标签 node.js express mongoose mocha.js angular-fullstack

我已经设置了一个简单的测试( Mocha 和应该),并且我正在测试我保存的报告是否与我得到的报告相同。我更喜欢使用 deep.equal 但由于 _id 不等于我陷入困境。

var report = new Report();

        describe('GET:id /api/reports', function () {

        beforeEach(function (done) {
            report.save(function (err, result) {
                if (err) return (done(err));
                result._id.should.eql(report._id);
                done();
            });
        });

        afterEach(function (done) {
            Report.remove().exec().then(function () {
                done();
            });
        });

        before(function (done) {
            Report.remove().exec().then(function () {
                done();
            });
        });


        it('should respond with the same report saved', function (done) {
            request(app)
                .get('/api/reports/' + report._id)
                .expect(200)
                .expect('Content-Type', /json/)
                .end(function (err, res) {
                    if (err) return done(err);
                    console.log(JSON.stringify(res.body));
                    console.log(JSON.stringify(report));
                    res.body._id.should.equal(report._id);

                    done();
                });
        });
    });

我得到的输出是

    {"_id":"55282d42cb39c43c0e4421e1","__v":0}
{"__v":0,"_id":"55282d42cb39c43c0e4421e1"}

1) GET:id /api/reports should respond with the same report saved:
     Uncaught AssertionError: expected '55282d42cb39c43c0e4421e1' to be 55282d42cb39c43c0e4421e1

如果我改用 == 它工作正常

(res.body._id == report._id).should.equal(true);

我最终想要的是 res.body (或其他与此相关的东西)深度等于初始报告。

最佳答案

假设您是 /api/reports/:id 的 Express 路由处理程序,使用 res.json() 发送报告, Mongoose 文档的问题是“字符串化”。当 mongoose 文档被字符串化时,ObjectId 会被类型转换为字符串,当解析回对象时,字符串不会自动转换回 ObjectId。

因此,如果您希望原始 Report 文档与 Express 返回的文档“深度相等”,则需要将其提交到相同的“转换过程”。该断言看起来像这样。

res.body.should.eql(JSON.parse(JSON.stringify(report)));

希望这对您有用。

关于node.js - 在express api中返回时,mongoose中_id的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29569932/

相关文章:

node.js - POST 请求未通过 (MERN)

javascript - 在 ejs 中制作类似组件的元素

javascript - 如何用另一个集合查询主集合[Mongoose]

node.js - mongolab 和 heroku 之间的连接需要 ssl 吗?

javascript - errmsg : 'Unsupported projection option: $push: { ... }' , 代码 : 2, codeName: 'BadValue' }

javascript - 在 Node.js 中,我找不到使用 URL 获取图像大小的 "require(' http')"依赖项

node.js - Socket.IO - 如何离线处理 Node.js

javascript - 如何解决语法错误: Unexpected token = after importing a class?

javascript - 异步给出回调已经调用错误?

javascript - 使用 nodejs 进行测试时,svgElement.getBoundingClientRect() 始终返回零