如何将一个Mongoose对象与一个JSON对象进行比较?
这是我的问题。
一方面,我有一个简单的对象表示一个Mongoose对象。
另一方面,我有一个来自数据库中的findOne
的Mongoose对象。
我想要做的是检查两个对象的两个属性之间是否有任何不同。 我们来考虑一下这种模型:
{ _id: 'abc', id: 'abc', things: [{ _id: 'def', id: 'def', other_things: [{ _id: 'ghi', id: 'ghi', foo: 'bar' }] }] }
我想比较myplainobject.things
和mydbobject.things
。
但是,使用underscore
, underscore
. _.isEqual(myplainobject.things, mydbobject.things)
总是失败。
这是由于第一个string
中的id和另一个ObjectID
中的id所致。
虽然有很多方法可以将ObjectID
与string
进行比较,但有没有比较对象的优雅方法? 或者我必须实现我自己的解决scheme,将遍历每个子文档,并手动比较属性?
由于我现在没有足够的信誉来为drinchev的回答添加评论,所以我会在这里添加它。 首先,使用toObject()
build议的toObject()
方法,然后使用类似https://stackoverflow.com/a/14368628/3365039 (稍作修改)的答案来确保密钥的顺序相同。
function compareKeys(a, b) { var aKeys = Object.keys(a).sort(); var bKeys = Object.keys(b).sort(); // Check that the objects contain the same keys. if (JSON.stringify(aKeys) !== JSON.stringify(bKeys)) { return false } // Check that the keys in each object contain the same values. for (const key in aKeys) { if (a[key] !== b[key]) { return false } } return true } compareKeys(mongooseModel.toObject(), jsObject)