javascript 猫鼬保存失败而没有错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20304855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:11:33  来源:igfitidea点击:

mongoose save fails without error

javascriptnode.jsmongoose

提问by Jonathan Miles

As the title suggests I'm having problems with mongoose save method, which fails but does not produce an error.

正如标题所示,我在使用 mongoose save 方法时遇到了问题,该方法失败但不会产生错误。

I actually know why it fails, which is down to the userId field being marked as required but not being provided... but I don't know why it doesn't throw an error. I've exhausted google and stackoverflow looking at similar suggestions with no luck, so throwing it open to anyone who can help me!

我实际上知道它为什么失败,这归结为 userId 字段被标记为必需但未提供......但我不知道为什么它不会引发错误。我已经筋疲力尽了 google 和 stackoverflow 寻找类似的建议但没有运气,所以把它扔给任何可以帮助我的人!

Here's the code...

这是代码...

Model.js

var mongoose = require('mongoose');

var TimeSchema = new mongoose.Schema({
    client: String,
    matter: String,
    activity: String,
    tags: String,
    description: String,
    comments: [String],
    startTime: Date,
    startTimeUTC: Number,
    endTime: Date,
    endTimeUTC: Number,
    duration: Number, 
    durationRnd: Number,    
    durationUnits: Number,  
    billable: Boolean,
    rate: Number,
    total: Number,
    user: String,
    userId: { type: mongoose.Schema.ObjectId, required: true }
}, {safe: true});

mongoose.model("Time", TimeSchema);


Controller.js

exports.addTime = function (req, res) {

    console.log('Adding time: ' + JSON.stringify(req.body));
    var time = new Time(req.body);
    time.save(function (err) {
        if (err) { res.send({'error' : err}); }
        res.send(time);
    });
}

EDIT- To clarify the callback is being called, take the following code for example.

编辑- 为了澄清正在调用的回调,以下面的代码为例。

exports.addTime = function (req, res) {

    console.log('Adding time: ' + JSON.stringify(req.body));
    var time = new Time(req.body);
    console.log("time = " + time);
    // TODO user
    time.save(function (err) {
        if (err) { handleError(res, err); }
        console.log("ok");
        Time.findById(time._id, function (err, found) {
            console.log("found = " + found);
        });
        res.send(time);

});

}

}

and here's the console output

这是控制台输出

Adding time: {"description":"test","client":"","matter":"","activity":"","rate":
"","startTime":"2013-11-30T19:58:43.000Z","startTimeUTC":"1385841523000","endTim
e":"2013-11-30T19:58:45.000Z","endTimeUTC":"1385841525000","startLocale":"19:58"
,"startTimeLocale":"19:58:43","endLocale":"19:58","endTimeLocale":"19:58:45"}
time = { description: 'test',
  client: '',
  matter: '',
  activity: '',
  rate: null,
  startTime: Sat Nov 30 2013 19:58:43 GMT+0000 (GMT Standard Time),
  startTimeUTC: 1385841523000,
  endTime: Sat Nov 30 2013 19:58:45 GMT+0000 (GMT Standard Time),
  endTimeUTC: 1385841525000,
  startTimeLocale: '19:58:43',
  endTimeLocale: '19:58:45',
  _id: 529a43750a366b6419000001,
  comments: [] }
ok
POST /api/times 200 14ms - 313b
found = null

采纳答案by Jonathan Miles

Problem solved, thanks to robertkelp.

问题解决了,感谢 robertkelp。

Here's my revised code in case if ever helps anyone, but it appears the error was being thrown I just wasn't handling it correctly.

这是我修改后的代码,以防万一,如果对任何人有帮助,但似乎抛出了错误,我只是没有正确处理它。

exports.addTime = function (req, res) {

    console.log('Adding time: ' + JSON.stringify(req.body));
    var time = new Time(req.body);
    time.save(function (err) {
        if (err) { 
            handleError(res, err);
        }
        else {
            res.send(time);
        }
    });
}

回答by Ali

It is very possible to run into this error by naively not connecting to the database. Has happened several times to me. Make sure your mongoose.connect()is in place.

天真地不连接到数据库很可能会遇到此错误。在我身上发生过几次。确保你mongoose.connect()的位置。

回答by shacharsol

My Problem was not solved by using findOne, it was solved by defining the fields i updated , in the model schema. so my code was like that:

我的问题没有通过使用 findOne 解决,而是通过在模型架构中定义我更新的字段来解决的。所以我的代码是这样的:

          User.findOne({email:data.userData.email}, function (err, user) {
                    if (!err && user!=undefined){
                        console.log(user);
                        var userDiscounts = user.discounts;
                        for(var i=0;i<userDiscounts.length;i++){

                            if (userDiscounts[i]!=undefined && userDiscounts[i].code=="XXXXXX"){
                                userDiscounts[i].claimed = true;

                                console.log('discount claimed');

                            }
                        }
                        user.discounts = userDiscounts;
                        user.fbDiscountClaimed = true;
                        user.save(function(err) {
                            if (err) console.log(err);
                            console.log('Saved Hashve-FB as claimed');


                        });
                    }


                });
            }
        }

But the schema of the discount and user model was missing the definition of types of user.discounts so i added the following:

但是折扣和用户模型的模式缺少 user.discounts 类型的定义,所以我添加了以下内容:

  var UserSchema = new Schema({
  name: String,
  email: { type: String, lowercase: true },
   role: {
   type: String,
   default: 'user'
 },
  hashedPassword: String,
  provider: String,
  salt: String,
  messages:[],
  discounts:[{
  "name": String,
  "description": String,
  "created_at": String,
  "updated_at": String,
  "code": String,
  "claimed": Boolean
    }
    ],
   facebook: {},
   fbDiscountClaimed:false,
    twitter: {},
  google: {},
  github: {}
  });

回答by xiaopf

UserSchema.pre('save',function(next){
  var currentDate=new Date();
  this.updatedAt=currentDate;
  if(!this.createdAt){
    this.createdAt=currentDate;
  };
  next();
});

When I use the .pre('save',fn)to create time, I forgot the next(), causing the data store to fail without error,I hope can help somebody!

当我使用.pre('save',fn)创建的时候,我忘记了next(),导致数据存储失败,没有错误,希望能帮到人!

回答by MalcolmOcean

I had a situation where the savecallback was getting called, but the document wasn't changing. I haven't yet tracked down the root cause (some sort of validation thing probably) but the problem had something to do with one of the changes I made. So I just tried the changes one by one until I found the culprit.

我遇到了save回调被调用的情况,但文档没有改变。我还没有找到根本原因(可能是某种验证),但问题与我所做的更改之一有关。所以我只是一一尝试更改,直到找到罪魁祸首。

(Feel free to edit this answer if you figure out more of this phenomenon)

(如果您发现更多这种现象,请随时编辑此答案)