我正在使用mongo作为后端构建Mean Stack应用程序。 我的猫鼬模型中有一个教会模式,如下所示:
{
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');
var sequenceGenerator = require('mongoose-sequence-plugin');
var unit = new Schema({
unit_id: {type: String},
unit_name: {type: String, unique: true},
unit_address: {type: String}
});
var schema = new Schema({
church_id: {type: String},
church_name: {type: String, required: true, unique: true},
email: {type: String, required: true, unique: true},
parishname: {type: String},
diocese: {type: String},
units: [unit],
church_reg_id: {type: String, required: true, unique: true},
address: {type: String},
city: {type: String},
zipcode: {type: Number},
state: {type: String},
church_contact_no: {type: Number}
});
schema.plugin(mongooseUniqueValidator);
schema.plugin(sequenceGenerator, {
field: 'church_id',
startAt: '0001',
prefix: 'CHURCH_',
maxSaveRetries: 3
});
module.exports = mongoose.model('Church', schema);
现在我正在尝试更新当前架构中已经拥有其他字段数据的单元子文档。更新代码如下:
router.patch('/addunit/:uname/:uaddress', function (req, res, next) {
console.log(req.params.uname);
Church.findOne({church_id: req.body.church_id}, function (err, church) {
if (err) {
return res.status(500).json({
title: 'No Church Details Found',
error: err
});
}
console.log(church.church_reg_id);
console.log(church.church_name);
church.units.push({
unit_name: req.params.uname,
unit_address: req.params.uaddress,
unit_id: req.body.church_id + "Unit_" + req.params.uname
});
console.log(church.units);
church.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Unit Added',
obj: result
})
});
});
});
现在的问题是代码运行成功,并且单位字段在后端成功更新,但在此之后我收到了以下错误。
D:\Church\node_modules\mongodb\lib\utils.js:123
process.nextTick(function() { throw err; });
^
TypeError: callback is not a function
at D:\Church\node_modules\mongoose\lib\model.js:267:5
at D:\Church\node_modules\mongoose\lib\model.js:195:9
at handleCallback (D:\Church\node_modules\mongodb\lib\utils.js:120:56)
at D:\Church\node_modules\mongodb\lib\collection.js:1062:5
at D:\Church\node_modules\mongodb-core\lib\connection\pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
请帮助找出问题所在。
答案 0 :(得分:0)
能够使用findOneAndUpdate查询成功更新文档,并使用$ addToSet在教会模式中添加子文档。
Church.findOneAndUpdate({church_id: req.body.church_id}, update1, options, function (err, church) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Unit Added',
obj: church
})
});
仍然不确定为什么model.save()查询会抛出错误。