Mongoose RESTful api object.id参考

时间:2017-07-21 21:58:16

标签: javascript mongodb mongoose

我尝试为todos应用程序构建RESTful api。

Todos计划:

const mongoose = require('mongoose');

const TodosScheme = new mongoose.Schema({
    id: String
});

module.exports = mongoose.model('Todos', TodosScheme);

任务计划:

const mongoose = require('mongoose');

const TaskScheme = new mongoose.Schema({
    id: String,
    todosID: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Todos'
    },
    content: String,
    isDone: Boolean
});

module.exports = mongoose.model('Task', TaskScheme);

因此,如果用户创建任务,它将成为某些Todos项目的参考。

我开始为create todos list编写路由

app.post('/api/todos/create', (req, res) => {
    newTodos = new Todos({});
    newTodos.save((err, todos) => {
        if (err) res.status(400).json(err);
        res.json(todos);
    });
});

现在我尝试写路线来创建任务

app.post('/api/todos/create/task', (req, res) => {
    const body = req.body;
    console.log(body);
    let newTask = new Task({
        todosID: body.todosID, //here i not sure!
        content: body.content || 'no content',
        isDone: body.isDone || false
    });

    newTask.save((err, task) => {
        if (err) res.status(400).json(err);
        res.json(task);
    });
});

所以我的问题是: 1)创建任务我需要传递三个参数:

内容:客户将从请求

传递

isDone:客户端将从请求

传递

todosID:X?客户?这是最好的方式吗?

2)如果客户端需要传递todosID,那么必须在Task方案中使用吗? 因为如果用户现在创建任务而没有todosID,他将创建没有引用的任务。

3)有更好的方法来编写方案todos app? 谢谢大家:))

1 个答案:

答案 0 :(得分:0)

/api/todos/create返回已创建的todos对象。它应包含_id属性。要创建任务,您应该在请求正文中发送todos._id content