Mongoose assign a collection to another

165 views Asked by At

I am trying to add a post to a user collection after the user was created with empty posts. I have tried with populate with no success .. any help is much appreciated.

// Post Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
 
const UserModel = require('./user-model');
 
let PostSchema = new Schema({
  author: {
    ref: 'users',
    type: Schema.Types.ObjectId
  },
  content: String,
  description: String,
  date: {
    default: new Date(),
    type: Date
  },
  title: String,
  updatedAt: {
    default:  new Date(),
    type: Date
  }
});

let PostModel = mongoose.model('posts', PostSchema);
module.exports = PostModel;
// User Model 
 
const mongoose = require('mongoose');
const { Schema } = mongoose;
 
const PostModel = require('./post-model');
 
let UserSchema = new Schema({
  name: {
    type: String
  },
  email: {
    lowercase: true,
    type: String,
    trim: true,
    unique: true
  },
  password: {
    type: String,
  },
  postList: [{
    ref: 'posts',
    type: Schema.Types.ObjectId
  }],
});

const UserModel = mongoose.model('users', UserSchema);
module.exports = UserModel;

// save post controller
exports.savePost = (request, response, next) => {
  let { author, description, title } = request.body;
  let post = new PostModel({ author, description, title }).save();
  UserModel.findById(author)
    .then((user) => {
      user.postList.push(post);
      // Still Fails
      // How can i assign the post to the user ?
  });
}

Is there any way of doing this other then push or populate ?

3

There are 3 answers

0
AudioBubble On BEST ANSWER

exports.savePost = (request, response, next) => {
  let { user, description, title } = request.body;

  let post = new PostModel({ user, description, title });

  post.save()
    .catch((error) => {
      if (error) 
        throw new Error(error);
    })
    .then((post) => {
      UserModel.findOneAndUpdate({ _id: user }, {$push: { postList: post._id } })
      .populate('postList')
      .catch((error) => {
        if (error) 
          throw new Error(error);
      })
      .then((user) => {
        user.postList.forEach((item, postion) => {
          console.log(`${item} -at ${postion} \n`);
        });
      });

  });

}

This is what i did and it worked after all. I don't know if this is the correct solution but this is working.

2
Giorgio Cerruti On

To solve this problem I prefer to use $push of mongo

UserModel.findOneAndUpdate({
    _id: author.id,
   {
        $push: {
                postList: post
            }
        }

});
2
Shaishab Roy On

You need to follow this process to save successfully

  1. Save post if success then
  2. Update user to push postId in postlist

can try this one

exports.savePost = (request, response, next) => {
  let post = new PostModel(request.body)

  post.save(function(err, data) {
    if(err) {
       //return error
    }
    // check by console your author is present or not
    // let author in your req.body
    let author = req.body.author
    UserModel.findOneAndUpdate({_id: author},{$push: {postList: post._id}},{new:true} function(error, user) {
        if(error) {
          // return error
        }
        console.log(user)
        // return success
    })
  });
}