【问题标题】:Issue with Mongoose Model.Save methodMongoose Model.Save 方法的问题
【发布时间】:2018-01-13 17:07:06
【问题描述】:

当我使用 post api 调用 'userInfo' 方法时,它总是给出一条消息 'userSchema.save' is not a function。

我在这里做错了什么?

var userModel = mongoose.model('user_details');

module.exports.userInfo = function (req, res) {

        var userSchema = new userModel();

        new Promise(function (resolve, reject) {

            userSchema.emailID= "smid"
            userSchema.loginPassword ="smpaswd"

            userSchema.contactAddress = [{
                addressType: "Communication",           
            }]

            userSchema.favourites = [{
                hospitalid: 1234,            
            }] 

            resolve();

        }).then(function () {
            userSchema.save(function (error, data) {
                if (error) {
                    logger.error("Error while inserting record : - " + error)
                    return res.json({ "Message": error.message.split(":")[2].trim() });
                }
                else {
                    return res.json({ "Message": "Data got inserted successfully" });
                }
            })
        }).catch(function (err) {
            return res.json({ "Message": err.message });
        })   
};

【问题讨论】:

  • 能否请您添加“确切”的错误信息?
  • 错误信息 - {"Message":"userSchema.save is not a function"}。它是从承诺的 catch 块中抛出的
  • 你能粘贴user_details的猫鼬模型模式定义吗

标签: node.js mongodb mongoose promise


【解决方案1】:

我猜您创建模型对象的方式不正确。看这个例子,在这个例子中,我们将模式定义作为“yourSchema”传递,因此您可能需要在对象创建中传递您的模式定义。

var Tank = mongoose.model('Tank', yourSchema);

var small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
})

// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
})

像这样的

//userSchema should exist there
var userModel = mongoose.model('user_details', userSchema);

【讨论】:

  • Schema 对象是正确的。我正在使用 mongoose.model('user_details');问题中没有显示。我想知道承诺实现是否有问题
  • 即使你的 Promise 实现有问题,错误也会有所不同。我要说的是 -> var userModel = mongoose.model('user_details');这条线有一些问题。我猜你需要在这个传递模式。像这样 -> var userModel = mongoose.model('user_details', yourUserSchema);
  • 类似于 userSchema.emailID="smid" ,我可以为子文档写 userSchema.contactAddress.addressType="Communication" 吗?我试过了,但它不起作用
  • 是的,你会写。你遇到了什么错误?
  • 它没有抛出任何错误。但是没有创建数组。
猜你喜欢
  • 1970-01-01
  • 2018-05-22
  • 2020-11-05
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 2019-05-03
  • 2014-12-16
  • 2015-09-18
相关资源
最近更新 更多