正如标题所示,我在使用mongoose的save方法时遇到问题,它失败了但没有产生错误。
实际上我知道为什么失败了,这是由于userId字段被标记为必需但未提供... 但我不知道为什么它不会抛出错误。我已经耗尽了谷歌和stackoverflow上类似建议的办法,没有找到解决方法,所以现在向任何能帮助我的人寻求帮助!
以下是代码...
实际上我知道为什么失败了,这是由于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);
});
}
编辑 - 为了澄清回调正在被调用,以以下代码为例。
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
err
是否未被设置,例如使用if (err) console.log(err)
这样的方式吗?另外,在调用handleError()
后,应该停止执行代码的其余部分(通常的做法是使用类似if (err) return handleError(...)
的方法)。 - robertklep