我有两个模式,一个是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 pre save hook中的userSchema.find方法
productSchema.pre('save', function (next) {
userSchema.findOne({'_id': userId}, function(err, user)
{
console.log(user);
});
}
但它返回错误。有人可以在这个问题上帮助我。
答案 0 :(得分:2)
你可以这样做
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
})
更好的方法是使用快递的路由器级中间件