简体   繁体   English

如何使trim() 函数在node.js 代码中工作,即使没有在mongoose 的模型模式中使用?

[英]How to make trim() function work in node.js code, even if not used in mongoose's model schema?

I've a mongodb collection which stores "Customers" data.我有一个存储“客户”数据的 mongodb 集合。 I need to trim the mobile number of a customer if there are any trailing or leading white spaces available.如果有任何可用的尾随或前导空格,我需要修剪客户的手机号码。 I've used trim() function to remove them.我使用了trim()函数来删除它们。 But am getting an error, trim() is not a function .但是我收到一个错误, trim() 不是一个函数

Here's my model schema:这是我的模型架构:

var schema = mongoose.Schema({
    name    : {type: String, required: true},
    email   : {type: String, required: true},
    mobile  : {type: String, required: true, index: false, unique: false});

module.exports = mongoose.model("customer", schema);

Here's the code where I've used trim function:这是我使用修剪功能的代码:

addNewCustomer: async function(payload){
  var customer = new Customer({
     name  : payload.name,
     email : payload.email,
     mobile: payload.mobile.trim()
  });
}

When I execute the above function, it is giving me the error.当我执行上述函数时,它给了我错误。 But if I use trim() at schema level, it is working fine.但是如果我在模式级别使用trim() ,它工作正常。

mobile  : {type: String, required: true, index: false, unique: false, trim: true});

What is the difference between using trim() in SCHEMA level and FUNCTIONALITY level?在 SCHEMA 级别和 FUNCTIONALITY 级别使用 trim() 有什么区别? Why it is not working when used in function?为什么在函数中使用它不起作用?

Have seen functional alternative 'cursor' syntax ala:看过功能性的替代“光标”语法ala:

db.collection.find({},{ "category": 1 }).forEach(function(doc) {
  db.collection.update(
    { "_id": doc._id },
    { "$set": { "category": doc.category.trim() } }
  );
})

Above example copied from: https://stackoverflow.com/a/46554968/2003321以上示例复制自: https : //stackoverflow.com/a/46554968/2003321

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM