如何访问另一个模型mongoose数据库中的一个模型模式
我有两个模式,一个是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 } });
当用户在collections中添加新产品时,他将填写产品架构中提到的所有字段。 我想在产品收集中用户添加新产品时validation用户collections中是否存在input的用户标识。 我试图访问productSchema pre save钩子中的userSchema.find方法
productSchema.pre('save', function (next) { userSchema.findOne({'_id': userId}, function(err, user) { console.log(user); }); }
但是它返回一个错误。 有人能帮我解决这个问题吗?
你可以这样做
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 })
更好的方法是使用快车的路由器级中间件