如果键不在猫鼬模式中,则返回信息

时间:2019-02-06 09:48:26

标签: node.js mongodb mongoose

我有一个带有多个参数的猫鼬模式,如果参数未知,我希望猫鼬返回一条消息。

例如,如果我有姓名和年龄,如果年龄不是必需的,但用户写agege,我想向用户返回警告,但我在猫鼬文档中找不到该警告。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您在后端编写代码,请不要编写不需要的内容。

例如,您的架构如下:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({

  name: {
    type: String,
    required: true
  },
  age:String //not required

和您的其余API

app.post('/user', (req,res) => {
 const newData = new UserSchema({
  name : req.body.name
  //although user post age, don't create age field, ignore that
 })
 newData.save().then().catch(err => console.log(err))
})

另一种方法是创建验证,如果用户输入了年龄,则发送响应(“不需要”)。

我希望这个线索能对您有所帮助。谢谢