Loopback JS切换MongoDB后null字段查询失效,求无需改查询的配置
null Filter Issues When Migrating LoopBack from MySQL to MongoDB I've run into this exact issue before when migrating LoopBack apps between SQL and NoSQL databases—this is all about how LoopBack's MongoDB connector handles null values by default.
The Root Cause
By default, LoopBack's MongoDB connector has the nullAsUndefined option set to true. This means any null values in your where filters get converted to undefined, which translates to a MongoDB query looking for documents where the field doesn't exist ({ fieldName: { $exists: false } }), rather than matching documents where the field is explicitly null (which aligns with MySQL's fieldName IS NULL behavior, matching both NULL values and effectively missing fields).
The Solution: Adjust MongoDB Datasource Configuration
To make your existing {filter:{where:{fieldName:null}}} queries work exactly as they did in MySQL, you just need to disable the nullAsUndefined option in your MongoDB datasource configuration. This tells the connector to preserve null values in your filters, matching MongoDB's native behavior for { fieldName: null }—which matches both documents where the field is null and documents where the field doesn't exist, perfectly mirroring MySQL's IS NULL behavior.
Example Configuration (datasources.json)
{ "yourMongoDatasource": { "name": "yourMongoDatasource", "connector": "mongodb", "url": "mongodb://localhost:27017/your-database-name", "nullAsUndefined": false } }
Example Configuration (datasources.js)
If you're using a JavaScript-based datasource config:
module.exports = { yourMongoDatasource: { connector: 'mongodb', url: 'mongodb://localhost:27017/your-database-name', nullAsUndefined: false } };
Verify the Fix
After updating the config, restart your LoopBack service. Your existing queries using fieldName: null will now behave identically to how they did in MySQL—no changes to your query code required.
内容的提问来源于stack exchange,提问作者user257980

