猫鼬验证查找关系时出错

时间:2020-10-07 16:17:55

标签: node.js mongoose

我正在使用猫鼬并尝试设置两个架构之间的关系,但是我收到ValidationError

 errors: {
    userId: ValidatorError: Path `userId` is required.
        at validate (C:\ShoppingApp\node_modules\mongoose\lib\schematype.js:1222:13)
        at C:\ShoppingApp\node_modules\mongoose\lib\schematype.js:1205:7
        at Array.forEach (<anonymous>)
        at ObjectId.SchemaType.doValidate (C:\ShoppingApp\node_modules\mongoose\lib\schematype.js:1150:14)
        at C:\ShoppingApp\node_modules\mongoose\lib\document.js:2439:18
        at processTicksAndRejections (internal/process/task_queues.js:79:11)
        at runNextTicks (internal/process/task_queues.js:66:3)
        at processImmediate (internal/timers.js:429:9) {
      properties: [Object],
      kind: 'required',
      path: 'userId',
      value: null,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'Product validation failed'
}
Error: Product validation failed: userId: Path `userId` is required.
    at ValidationError.inspect (C:\ShoppingApp\node_modules\mongoose\lib\error\validation.js:47:26)       
    at formatValue (internal/util/inspect.js:698:31)
    at inspect (internal/util/inspect.js:269:10)
    at formatWithOptions (internal/util/inspect.js:1870:40)
    at Object.Console.<computed> (internal/console/constructor.js:281:10)
    at Object.log (internal/console/constructor.js:291:61)
    at C:\ShoppingApp\controllers\admin.js:26:15
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at runNextTicks (internal/process/task_queues.js:66:3)
    at processImmediate (internal/timers.js:429:9) {

这是我的两个模式文件:-

产品架构文件:-

const mongoose = require('mongoose');

const Schema = mongoose.Schema

const productSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  imageUrl: {
    type: String,
    required: true
  },
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
});

module.exports = mongoose.model('Product', productSchema);

用户架构文件:-

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    cart: {
        items: [{
            productId: { type: Schema.Types.ObjectId, ref: 'Product', required: true },
            quantity: { type: Number, required: true }
        }]
    }
})

module.exports = mongoose.model('User', userSchema);

我使用此架构发布内容的地方是:-

exports.postAddProduct = (req, res, next) => {
  const title = req.body.title;
  const imageUrl = req.body.imageUrl;
  const price = req.body.price;
  const description = req.body.description;
  const product = new Product({
    title: title, price: price, description: description, imageUrl: imageUrl, userId: req.user
  });
  product.save()
    .then(result => {
      console.log('Created Product');
      res.redirect('/admin/products');
    })
    .catch(err => {
      console.log(err);
    })
};

当我设置为required时,会发生此错误:User Schema文件中为true。如果我删除了必填项:true,那么我没有收到任何错误,但是我的userId传递为null。我没有userId。 所以,我不明白为什么会这样。

1 个答案:

答案 0 :(得分:0)

您尝试使用userId:req.user。但是要做到这一点,首先您必须将用户添加到请求对象中。您可以在中间件中进行快速表达。通常,您必须在项目中实现用户授权,如果授权通过,则可以向请求对象添加用户信息,如果授权失败,则必须重定向到登录页面。但是,目前最好的选择是确保一切正常,然后从数据库中更改userId:req.user,其中userId:存在的userId。在这种情况下,验证必须很好。