user3869304
user3869304

Reputation: 873

How to insert data in to related mongoose Schemas?

I am trying to create an api endpoint in nodejs to insert data in mongodb. I have got two mongoose schemas which are related to each other that`s why i am relating these two schemas like below:

Posts schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PostSchema = mongoose.Schema({
    title: { type: String, trim: true, required: true},
    description: { type:String, required: true },
    created_at: { type: Date, default: Date.now },
    author: {type: Schema.ObjectId, ref: 'Author', required: true},
});

const Post = module.exports = mongoose.model('Post', PostSchema);

Authors Schema:

const mongoose = require('mongoose');

const AuthorSchema = mongoose.Schema({
    fullname: { type: String, trim: true, required: true},
    address: { type: String, required: true },
    phone: { type: Number, required: true },
    email: { type: String, required: true },
    created_at: { type: Date, default: Date.now }
});

const Author = module.exports = mongoose.model('Author', AuthorSchema);

Now i can easily insert data for authors schema

Authors.js:

router.post('/', (req, res, next) => {
  let newAuthor = new Authors({
    fullname: req.body.fullname,
    address: req.body.address,
    phone: req.body.phone,
    email: req.body.email
  });

  newAuthor.save((err, user) => {
    if(err) {
      res.json({
        success: false,
        msg: "Failed to add author"
      });
    } else {
      res.json({
        success: true,
        msg: "Author added successfully"
      });
    }
  }); 
});

But for posts i am stuck in here

posts.js:

router.post('/', (req, res) => {
    var newPost = new Posts({
        title: req.body.title,
        description: req.body.description,
        author: 
    })
})

main problem is how to get author??

Upvotes: 2

Views: 3977

Answers (2)

Govind Rai
Govind Rai

Reputation: 15800

On the page where you allow users to create posts, you need to pass the author's id along with the rest of the post details. Then you can simply refer to the author's id by whatever you chose to send it as (i.e. authorId).

If you are using a serializer that takes all the values from your form and nicely packages them, then insert a hidden input field that stores the author's id, so you can capture that as well. For example:

<input type="hidden" name="authorId" value={user._id} />

Otherwise, if you are manually packaging the form field values, then just add the author's id as another property in the response object. Not sure what you're doing to send the request but say you were using the axios library to send an ajax post to your endpoint you could do this to easily add the author to the response:

const title = document.getElementByNames("title")[0].value
const description = document.getElementByNames("description")[0].value
const author = document.getElementByNames("authorId")[0].value
axios.post("/posts", {title: title, description: description, author: authorId}).then(res => console.log(res))

Upvotes: 0

Shaishab Roy
Shaishab Roy

Reputation: 16805

You can set author id in author field.

// you can set authorId in req.body and use that
router.post('/', (req, res) => {
    var newPost = new Posts({
        title: req.body.title,
        description: req.body.description,
        author: req.body.authorId
    })
});

OR you can set author id in route path and use req.params.authorId

// for that route from ui call should be like 
// var userId = 4654654545454
// $http.post('/'+userId)....

router.post('/:authorId', (req, res) => {
    var newPost = new Posts({
        title: req.body.title,
        description: req.body.description,
        author: req.params.authorId
    })
});

Upvotes: 1

Related Questions