你如何一次保存到三个系列?

时间:2018-01-23 21:26:30

标签: node.js mongodb mean-stack

我正在建立我的第一个平均堆栈应用程序。它是一个评论网站,包含三个模型:用户,评论和公司。

当我进行审核时,我希望将新审核保存到“审核”中。收集,并通过参考被审查的公司和撰写评论的用户连接该评论。我还希望用户持有对评论的引用,并希望公司持有对其所有评论的引用。这是我的模特:

审核

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

const reviewSchema = new Schema ({

  companyName: String,
  companyId: { type: Schema.Types.ObjectId, ref: 'Company'},
  starRating: Number,
  subject: String,
  commentBody: String,
  createdBy: { type: Schema.Types.ObjectId, ref: 'User'},

});


const Review = mongoose.model("Review", reviewSchema);
module.exports = Review;

公司

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

const companySchema = new Schema ({

  companyName: String,
  about: String,
  basedIn: String,
  materialOrigins: [String],
  productRange: [String],
  category: String,
  reviews: [ {type: Schema.Types.ObjectId, ref: 'Review'} ],
  socialRating: Number,
  environmentalRating: Number,
  priceRange: Number

});


const Company = mongoose.model("Company", companySchema);
module.exports = Company;

用户

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

const userSchema = new Schema ({
  email: String,
  firstName: String,
  lastName: String,
  password: String,
  image: Object,
  aboutText: String,
  reviews: [ { type: Schema.Types.ObjectId, ref: "Review" } ]
  // comments: { type: Schema.Types.ObjectId, ref: 'Comment' }

});

const User = mongoose.model("User", userSchema);
module.exports = User;

这是我当前的路线,目前将评论保存到集合并附加用户。但是,用户没有收到审核。

路线

router.post('/:category/:company', (req, res) => {

  var subject = req.body.subject;
  var commentBody = req.body.commentBody;
  var starRating = req.body.starRating;
  var userId = req.body.userId;

  if(!subject || !commentBody || !starRating) {
    res.status(400).json({ message: "Subject, comment body, and star rating are required." });
    return;
  }

  var newReview = Review({
    starRating,
    subject,
    commentBody,
    userId
  });


     User.findById(userId, {
     }, (err, user) => {
       if (err) {
         return res.send(err);
       } else {

         console.log("checking out user in route", user);
         user.reviews.push(newReview);
         user.save();

         newReview.save((err, review) => {
              if (err) {
                return res.status(400).json({ message: err });
              } else {
                res.status(200).json({ message: 'Review saved', review });
              }
            });

       }
     });

我没有尝试过添加公司,因为我一次尝试做一件事。我一直在查看“填充”,但所有文档似乎只能同时使用两个模型。有可能一次做三个吗?或者我是否过于复杂?

如果这一切都过于复杂,请道歉。我一般都是MongoDB和MEAN堆栈的新手。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

好的,我做到了,因为任何登陆此页面的人都会在将来想到同样的事情。

这是我的路线:

router.post('/:category/:company', (req, res, next) => {

  var companyName;
  var companyId;

  var subject = req.body.subject;
  var commentBody = req.body.commentBody;
  var starRating = req.body.starRating;
  var createdBy = req.body.createdBy;


  if(!subject || !commentBody || !starRating) {
    res.status(400).json({ message: "Subject, comment body, and star rating are required." });
    return;
  }

  var newReview = Review({
    starRating,
    subject,
    commentBody,
    createdBy
  });

 //I need the companyId and companyInfo for later use in my review save.  I'm calling the company with the name I have from my params, and setting the id and name with the received data from Mongo.

  Company.findOne({"companyName": req.params.company}, (err, company) => {
    if (err) {
      return res.status(400).json({ message: err });
    } else {
      this.companyName = company.companyName;
      this.companyId = company.id;
    }
  });

         newReview.save((err, review) => {

//Push the review id to the user
              if (err) {
                return res.status(400).json({ message: err });
              } else { User.findByIdAndUpdate({_id: createdBy },{$push:  {reviews: review.id} }, (err) => {
                  if (err) {
                    console.log("There was an error pushing review to user");
                    next(err);
//Push the review id to the company
                  } else {  Company.findOneAndUpdate({ "companyName": req.params.company}, {$push: {reviews: review.id}}, (err, company) => {
                      if (err) {
                        console.log("There was an error pushing review to company");
                        next(err);
                      } else {

                        //Updates the review by setting companyId and companyName properties to review for Mongo
                        Review.update({_id: review.id}, {$set: {companyId: this.companyId, companyName: this.companyName}}, (err, changes) => {
                          if(err) {
                            return res.status(400).json({message : err});
                          } else {
                            console.log("updating review successfully with company info", changes);
                          }
                        });

                        console.log ("Review successfully saved");

                        res.json({
                          review: review,
                        });

            }
          });

        }
      });

    }


});
});

如果有人对如何更好/更有效地完成此操作有任何反馈,请告诉我。欢呼声。