【问题标题】:Type of _id in mongoose wrong when returning in express api在 express api 中返回时,mongoose 中的 _id 类型错误
【发布时间】:2015-06-16 16:11:01
【问题描述】:

我已经设置了一个简单的测试(mocha 和 should),我正在测试我保存的报告是否与我得到的报告相同。我更喜欢使用 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(或与此相关的其他内容)深度等于初始报告。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    希望这对你有用。

    【讨论】:

    • 你的回答让我走上了正确的道路,编辑它以获得正确的语法并标记完成。 res.body.should.eql(JSON.parse(JSON.stringify(report)));
    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2021-11-30
    • 2018-02-27
    • 2018-04-22
    • 2019-07-09
    • 2020-09-16
    相关资源
    最近更新 更多