有一个API如下。
这里省略了try catch。
exports.test = async(req,res) => {
const {clientId} = req.body;
// There is a function that makes an object to use repeatedly.
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
clientId,
reason: arg1,
});
return errorLogs;
}
errorReason("server error").save();
这是 clientId 的类型。
clientId: mongoose.Schema.Types.ObjectId
当我可以将 clientId 的 obejctId 或空字符串作为 request.body 传递时。
但是当我发送空字符串时,会出现错误。
validation failed: clientId: Cast to ObjectID failed for value \"\" at path \"clientId\"
如何使 errorReason 的功能正确?我不想为 clientId 保存“null”或“空字符串”,即使 clientId 是空字符串。
我希望当 clientId 为空字符串时,“new ErrorLogs”没有 clientId。
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
reason: arg1,
});
return errorLogs;
}
非常感谢您阅读它。
最佳答案
您可以通过使架构中的 required
字段使用一个函数来实现此目的。该函数根据类型决定该字段是否为必填字段。这将允许您保存一个空字符串。
如果你想保存一个空字符串:
保存空字符串:
const mongoose = require('mongoose');
const errorSchema = new mongoose.Schema({
clientId: {
type: mongoose.Schema.Types.ObjectId,
required: function(){
return typeof this.clientId === 'string' ? false : true
},
}
});
const Errors = mongoose.model('errors', errorSchema)
更新:我似乎误解了您的意图。如果您只想不在文档中设置字段 clientId
,请在有空字符串时将 undefined
传递给架构。 Mongoose 不会保存该字段(除非您需要它,在这种情况下 mongoose 会抛出错误)
从保存的文档中排除空字符串字段:
function errorReason(arg1) {
const errorLogs = new ErrorLogs({
clientId: clientId || undefined, // handles '', undefined, null, NaN etc
reason: arg1,
});
return errorLogs;
}
errorReason("server error").save();
关于javascript - 使用 mongoose 时如何不通过函数传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59463147/