I
I
izzerador2017-02-26 20:32:27
MongoDB
izzerador, 2017-02-26 20:32:27

How to pass object to list of mongoose objects?

There is a user model

const UserSchema = mongoose.Schema({
  name: {
    type: String
  },
  email: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  posts: [{
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Post'
  }]
});

she apparently has posts.
there is a post model
var PostSchema = new Schema({
    post: {
        type: String,
        required: true
    },
    author: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    createdAt: {type: Date, default: Date.now},
    likes: {type: Number, default: 0}

});

she has an avor, I convey the author in a simple way =
router.post('/create-post', passport.authenticate('jwt', {session:false}), function (req, res, next)  {
  var post = new Post();
  post.post = req.body.post;
  post.author = req.user._id;
  post.save(function (err) {
    if (err)
        res.send(err);
    res.json({success: 'Post created ID:' + post._id, postedBy: post.author});
  });
});

How do I pass all create posts to the user's posts ?
Forgive me for such stupid questions, but I just can’t get it ...
Thank you in advance ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wasya UK, 2017-05-03
@dmc1989

I think here you will find what you need https://docs.mongodb.com/manual/reference/operator...
When creating a post, enter its ID using push to all user posts

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question