gpt4 book ai didi

javascript - Mongoose 保存失败且没有错误

转载 作者:IT老高 更新时间:2023-10-28 23:05:57 24 4
gpt4 key购买 nike

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

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

这是代码...

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 - 为了说明回调被调用,以下面的代码为例。

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

});

}

这是控制台输出

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

最佳答案

天真地没有连接到数据库很可能会遇到这个错误。在我身上发生了好几次。确保您的 mongoose.connect() 就位。

关于javascript - Mongoose 保存失败且没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com