Javascript 使用mongoose时如何不通过函数传递值
有一个api,如下所示。Javascript 使用mongoose时如何不通过函数传递值,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,有一个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,
此处省略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
当我可以将obejctId或clientId的空字符串作为request.body传递时。但当我发送空字符串时,会发生错误 验证失败:clientId:值\“\”的转换为ObjectID失败 在路径“clientId”处 我怎样才能使errorReason的功能正确?我不想为clientId保存“null”或“空字符串”,即使clientId是空字符串
当clientId为空字符串时,我希望没有用于“newerrorlogs”的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();
您应该使用下面这样的代码
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 : clientId, // add here clientId for asign clientId to field
reason: arg1,
});
return errorLogs;
}
if(!!clientId){ //Here !! means not equal to blank,null,undefine and 0
errorReason("server error").save();
}
非常感谢。但是如果是空字符串,我不想保存。@DDDD我已经更新了答案。只需在执行代码之前检查
clientId
是否为空字符串否?或者,当字段clientId
为空字符串时,您是否试图说不想保存该字段?