简体   繁体   English

保存Data Express / Mongoose时引用其他模型

[英]Referencing Other Models when Saving Data Express/Mongoose

I have a simple express app where users can log in and post pictures of mountains. 我有一个简单的快递应用程序,用户可以登录并发布山的图片。 I'm having an issue saving the posts the users add. 保存用户添加的帖子时出现问题。 Specifically, the user id that is referenced from another schema(user schema). 具体来说,是从另一个架构(用户架构)引用的用户ID。 When I submit the form, I get an undefined error on the "._id" and I'm not sure how to go about fixing it. 提交表单时,“ ._ id”出现未定义的错误,我不确定如何解决它。

Below are my model schemas. 以下是我的模型架构。

const userSchema = new Schema({
    name: String,
    email: String,
    username: String,
    password: String,
});



const canyonSchema = new Schema({
     canyon: String,
   image: String,
   description: String,
   cost: Number,
   createdAt: { type: Date, default: Date.now },
   author: {
      id: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "User"
      },
      username: String
   }
});
const Canyon = mongoose.model("Canyon", canyonSchema);
module.exports = Canyon;

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

Here is the logic that is supposed to save the information to mongo. 这是应该将信息保存到mongo的逻辑。 When I run, I get a "._id undefined". 运行时,我得到一个“ ._id未定义”。 Any help. 任何帮助。


    const User = require('../models/user');
    const Canyon = require('../models/Canyon');

    router.post("/add", , function(req, res){

     if(req.body.canyon &&
        rea.body.image &&
        req.body.description){

        const newCanyon = {
            canyon: req.body.canyon,
            image: req.body.image,
            description: req.body.description,
            author: {
                id: req.user._id,
            }, username: req.user.username
          };

          Canyon.create(newCanyon, function(error, canyon){
            if(error){
                return next(error)
            } else {
                req.session.userId = user._id;
                return res.redirect('/profile')
            }
          });
     } else {
        const err = new Error('All fields required.');
          err.status = 400;
          return next(err);
     }

      });

In your model schema, instead of 在您的模型架构中,

const canyonSchema = new Schema({
 canyon: String,
 image: String,
 description: String,
 cost: Number,
 createdAt: { type: Date, default: Date.now },
 author: {
  id: {
     type: mongoose.Schema.Types.ObjectId,
     ref: "User"
  },
  username: String
  }
});

Make the author itself the reference: 请作者自己作为参考:

const canyonSchema = new Schema({
 canyon: String,
 image: String,
 description: String,
 cost: Number,
 createdAt: { type: Date, default: Date.now },
 author: { type: mongoose.Schema.ObjectId, ref: 'User', index: true },
 });

To create a canyon object, 要创建峡谷对象,

const newCanyon = {
        canyon: req.body.canyon,
        image: req.body.image,
        description: req.body.description,
        author: req.user._id
      };

To get the user information embedded in the canyon object when query on canyons, just populate the author in the query, 要在对峡谷进行查询时将用户信息嵌入到canyon对象中,只需在查询中填充作者,

Canyon.findById(id).populate('author').exec()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM