任务信息架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var taskInfo = mongoose.Schema({
isactive:{type:Boolean},
taskobject:{type:String},
taskdetails:{type:String},
iscompleted:{type:Boolean}
});
var TaskInfo = mongoose.model('TaskInfo', taskInfo);
module.exports.TaskInfo = TaskInfo;
module.exports.TaskInfoSchema = taskInfo;
任务架构:
var mongoose = require('mongoose');
var TaskInfoSchema = require("./taskinfo.js").TaskInfoSchema
var Schema = mongoose.Schema;
// Task schema
var taskSchema = mongoose.Schema({
tasktype : {type: String},
createdon : {type: Date, default: Date.now},
//createdby : {type: Schema.Types.ObjectId,ref: 'User'},
//visitedby : [{type: Schema.Types.ObjectId,ref: 'User'}],
taskinfo : [TaskInfoSchema]
});
module.exports = mongoose.model('Task', taskSchema);
这是路由文件/ Controller :
var TaskInfo = require('../models/taskinfo.js').TaskInfo;
var Task = require('../models/task.js');
var config = require('../../config');
module.exports = function (app, express) {
var api = express.Router();
//GET method is for fetching all the tasks from the database,
api.get('/taskdb', function (req, res) {
//console.log("____");
Task.find({}, function (err, taskdb) {
if (err) {
res.send(err);
return;
}
res.json(taskdb);
});
});
//POST method is for saving all the tasks to the database,
api.post('/tasks', function (req, res) {
var task = {};
task.tasktype = req.body.tasktype;
task.taskinfo = [];
for (var i = 0; i < req.body.taskInfo.length; i++) {
console.log(i);
var taskInfo = new TaskInfo(req.body.taskInfo[i]);
task.taskinfo.push(taskInfo);
}
var taskObj = new Task(task);
taskObj.save(function (err) {
if (err) {
res.send(err);
return;
}
res.json({
message: 'Task has been created'
})
});
});
return api
}
我正在尝试添加 REST api 来更新值,每次遇到错误时,请有人告诉我数组是如何更新的,如果您发现它太基础并且不应该在这里询问,请建议我一些好的资源。
这是我的更新操作代码:
api.use('/tasks/:taskId',function(req, res, next){
Task.findById(req.params.taskId, function(err, task){
if(err){
res.send(err);
return;
}
else if(task)
{
req.task = task;
next();
}
else
{
res.status(404).send ('no task found with such details');
}
});
});
api.patch ('/tasks/:taskId',function(req,res){
if(req.body._id)
delete req.body._id;
for(var p in req.body)
{
req.tasktype[p] = req.body[p];
}
for(var p in req.body)
{
req.taskInfo[p] = req.body[p];
}
req.taskobj.save(function(err){
if(err){
res.send(err);
return;
}
res.json({message:'Task edited & updated '})
});
});
您可以使用 $set 运算符更新文档
1) 如果你想根据子文档id更新子文档
var id = taskInfoId;
here i am going to update field "isactive" of particular taskinfo
Task.update({"taskinfo._id":id},{$set:{"isactive":true}},function(err,success){
if(err){
}else{
}
});
2) 如果您想根据父文档 ID 更新子文档,则
var taskId = taskId;
Task.update({"_id":taskId},{$set:{"isactive":true}},function(err,success){
if(err){
}else{
}
});
我是一名优秀的程序员,十分优秀!