【问题标题】:Referencing Other Models when Saving Data Express/Mongoose保存数据时引用其他模型 Express/Mongoose
【发布时间】:2019-07-31 01:48:25
【问题描述】:

我有一个简单的快递应用程序,用户可以在其中登录并发布山脉图片。我在保存用户添加的帖子时遇到问题。具体来说,是从另一个模式(用户模式)引用的用户 ID。当我提交表单时,我在“._id”上收到一个未定义的错误,我不确定如何修复它。

以下是我的模型架构。

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 

这是应该将信息保存到 mongo 的逻辑。当我跑步时,我得到一个“._id undefined”。任何帮助。


    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);
     }

      });

【问题讨论】:

  • 您在哪里存储用户数据?当您从 req.user 检索它时,它具有未定义的值。因此,如果您从表单传递值,则使用 req.body 或在会话中存储用户详细信息。

标签: javascript node.js express mongoose


【解决方案1】:

在您的模型架构中,而不是

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 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 },
 });

要创建一个峡谷对象,

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

在canyons上查询时要获取canyon对象中嵌入的用户信息,只需在查询中填写作者即可,

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

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2018-05-31
    相关资源
    最近更新 更多