Reputation: 388
I would like to add a post and then if succeeded, push it's ref to user collection. That's how I'm doing this:
That's mine "app.js" file which contains User and Post Schema.
const mongoose=require('mongoose');
mongoose.connect("mongodb://localhost:27017/blog_demo", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
//post-{title,content}
var postSchema=new mongoose.Schema({
title:String,
content:String
});
var Post=mongoose.model('Post',postSchema);
//user-{email,name}
var userSchema=new mongoose.Schema({
email:String,
name:String,
posts:[postSchema]
});
var User=mongoose.model('User',userSchema);
//Create data
var newUser=new User({
email:'[email protected]',
name:'heromi'
});
newUser.posts.push({
title:'reflections on apples',
content:'They are delicious'
});
newUser.save(function(err,user){
if(err){
console.log(err)
}else{
console.log(user)
}
});
User.find({name:'heromi'},function(err,user){
if(err){
console.log(err)
}else{
user.posts.push({
title:'3 thing I hate',
content:'voldemort,voldemort,voldemort'
});
user.save(function(err,user){
if(err){
console.log(err)
}else{
console.log(user)
}
});
}
});
The problem is when I'm trying to push the post to user.
user.posts.push(..)
I get this error:
TypeError: Cannot read property 'push' of undefined
Any kind of help will be appreciated.Thanks for your time.
Thanks in advance .
Upvotes: 1
Views: 62
Reputation: 121
User.find
returns an array of documents who matche with you query object. If you want only one result, use User.findOne
instead or check if user.length > 0
and try user[0].posts.push(...)
Upvotes: 1