【问题标题】:How to access one model Schema in another model mongoose database如何访问另一个模型猫鼬数据库中的一个模型架构
【发布时间】:2017-04-11 19:13:54
【问题描述】:

我有两种模式,一种是 user.js 文件中的用户模式,另一种是 product.js 文件中的产品模式

我在 user.js 文件中的用户架构如下:

var userSchema = new Schema({
    firstname: {
        type: String,
        required: true
    },
    lastname: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    mobileno: {
        type: Number,
        unique: true,
        required: true
    },
    facebookid: {
        type: String
    },
    userimage: {
        type: String
    }
});

我正在使用 mongoose-auto-increment 模块覆盖自动生成的 _id,以在用户集合中自动增加 userId。

我在product.js文件中的产品架构如下:

var productSchema = new Schema({
    userId: {
        type: String,
        required: true
    },
    productName: {
        type: String,
        required: true
    },
    productId: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        unique: true,
        required: true
    },
    prodcutImage: {
        type: String
    }
});

当用户将新产品添加到集合中时,他将填写产品架构中提到的所有字段。当用户在产品集合中添加新产品时,我想验证输入的 userId 是否存在于用户集合中。 我尝试在 productSchema 预保存挂钩中访问 userSchema.find 方法

productSchema.pre('save', function (next) {
    userSchema.findOne({'_id': userId}, function(err, user)
    {
        console.log(user);
    });
}

但是它返回一个错误。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 错误是什么?
  • 查看正确的错误并发布..我认为你是什么意思.????

标签: node.js mongodb express mongoose mongoose-schema


【解决方案1】:

你可以这样做

app.get('/user/:id', function (req, res, next) {
      userSchema.findOne({'_id': userId}, function(err, user)
    {
        if(user){
           next()
               }else{
                    res.json("user id is not valid");
                    }
    });      
    }, function (req, res, next) {
      // code to add your product in product schema
    })

更好的方法是使用express的Router级中间件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多