【问题标题】:node.js mongoose TypeError: set is not a functionnode.js mongoose TypeError:设置不是函数
【发布时间】:2018-06-14 22:29:00
【问题描述】:

Node.jsMongoose 的新手。 在找到相关对象后尝试执行基本的set 操作,但是我收到以下错误:

TypeError: {found object}.set 不是函数。

以下是导致错误的代码:

    UserProfile.find({"user": req.params.id}, function (err, userProfile) {
    if (err) {
      console.log("Saving User profile - Error finding user");
    } else { // no error
      if (userProfile) { // if userProfile is found
        console.log("Saving User profile - userProfile found for user: " + userProfile);

        userProfile.set ({
          gender: req.body.gender,
          dob: req.body.dob,
          phone: req.body.phone,
          phone2: req.body.phone2,
          state: req.body.state,
          country: req.body.country
        });
      }
    }
  });

以下是我收到的错误:

TypeError: userProfile.set 不是函数

如果我尝试在基于相同模型创建的新对象上使用“set”函数,它可以正常工作

var userProfile = new UserProfile ();
userProfile.set ({
  gender: req.body.gender,
  dob: req.body.dob,
  phone: req.body.phone,
  phone2: req.body.phone2,
  state: req.body.state,
  country: req.body.country
});

以下是型号:

var mongoose = require("mongoose");
var UserProfileSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    gender: String,
    phone: String,
    phone2: String,
    dob: Date
});


module.exports = mongoose.model ("UserProfile", UserProfileSchema);

【问题讨论】:

  • 您有没有想过将 userProfile 记录到控制台以查看它是什么?

标签: javascript node.js mongodb mongoose


【解决方案1】:

使用findOne 而不是find。前者返回一个对象作为回调中的第二个参数,后者返回一个数组作为回调中的第二个参数。

【讨论】:

    【解决方案2】:

    .find 返回一个文档数组。尝试使用 .findOne 返回第一个找到的文档

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 2020-12-02
      • 2020-08-08
      • 2018-03-19
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      相关资源
      最近更新 更多