Reputation: 1258
I have been trying to use populate in mongoose, and my current idea is to check if a particular document is present in MongoDB, if it is then, the pre-save hook should check and rather then creating a new Document, it should just push it to the refs, so that I can populate later.
Now, the ref is being saved in MongoDB, however, how to check if the document which I am trying to save is there in mongo in pre save(or any other more suitable method)
This is the schema.
var Userschmea = new mongoose.Schema({
user:String,
posts:[{
type:mongoose.Schema.Types.ObjectId,
ref:'Post'
}]
})
var PostSchema = new mongoose.Schema({
content:String,
author:[{
type:mongoose.Schema.Types.ObjectId,
ref:'Author'
}]
})
Userschmea.pre('save',(next)=>{
//what to do here
next()
})
var Post = mongoose.model('Post',PostSchema);
var User = mongoose.model('User',Userschmea);
This is the endPoint by which I am trying to save:
app.post('/save/user',(req,res)=>{
console.log(req.body);
//Can i access this in my pre-save
const newUser = new User({
user: req.body.user
})
newUser.save((err)=>{
const newPost = new Post({
content:req.body.content,
author: newUser._id
})
newPost.save((err)=> {
if(err) {
return res.send(err);
}
})
if(err){
console.log(err);
return res.send(err);
}
})
return res.send(req.body.user);
})
Upvotes: 0
Views: 193
Reputation: 4210
You can use findOne
method with some unique key to check whether user is exists or not. I have used here email
.
Userschmea.pre('save',(next)=>{
var self = this;
Userschmea.findOne({email : this.email}, 'email', function(err, results) {
if(err) {
next(err);
} else if(results) {
self.invalidate("user", "user is exists");
next(new Error("User is already exists"));
} else {
next();
}
});
})
Hope this help!
====== UPDATE =====
Q: this
is coming empty.
Ans:
Function expressions are best for object methods while Arrow functions are best for callbacks or methods like map, reduce, or forEach.
So, Don't use arrow function in this case to access global scope.
Upvotes: 1