【问题标题】:CRUD on nested schemas using Mongoose使用 Mongoose 对嵌套模式进行 CRUD
【发布时间】:2015-03-10 16:37:18
【问题描述】:

我正在尝试使用 Mongoose 为 mongodb 子文档设置我的 nodejs 应用程序,但无法弄清楚如何访问嵌套对象的 _id。我只能获取父 ObjectId。我可以对新的子对象执行 .push,但不能对现有的子对象执行简单的 get、put 或 delete。

这是我的架构:

//new user model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// Task schema
var taskSchema = mongoose.Schema({
        clientEasyTask             : { type: String },
        clientHardTask         : { type: String },
        clientStupidTask      : { type: String }
});

var userSchema = new mongoose.Schema({
  email: { type: String, unique: true, lowercase: true },
  password: String,

  task             : [taskSchema]
});

module.exports = mongoose.model('Task', taskSchema);
module.exports = mongoose.model('User', userSchema);

这是我的路线:

'use strict';

var isAuthenticated = require('./middleware/auth').isAuthenticated,
isUnauthenticated = require('./middleware/auth').isUnauthenticated;

var User            = require('./models/user');
var Task            = require('./models/user');

// Create user.task

module.exports = function (app, passport) {

  app.post('/api/tasks', isAuthenticated, function (req, res) {

    var userEmail = req.body.email;
    var easyTask = req.body.easyTask;

    User.findOne({ 'email' :  userEmail }, function(err, user) {
      console.log('found user and defining status and data');
      var status;
      var data;

      if (err) {
        status = 'error';
        data = 'unknown error occurred';
      }
      if (user === null) {
        status = 'error';
        data = 'user not found';
      } else {
        status = 'ok';
        data = user;
      }

      user.task.push({
        clientEasyTask: easyTask
      });

      user.save();

      res.json({
        response: {
          'status': status
        }
      });
    });
  });


// Get one user.task
  app.get('/api/tasks/:id', function (req, res) {
      return Task.findById(req.params.id, function(err, task) {

      if(!task) {
        res.statusCode = 404;
        return res.send({ error: 'Not found' });
      }

      if(!err) {
        return res.send({ status: 'OK', task:task });
      } else {

        res.statusCode = 500;
        console.log('Internal error(%d): %s', res.statusCode, err.message);
        return res.send({ error: 'Server error' });
      }
    });
  });
};

我正在使用 Postman 测试所有内容,因此没有前端代码。当我传递任务的 _id(嵌套在用户中)时,当我在“/api/tasks/:id”上调用 Get 时收到 null。我怎样才能只获得特定的任务?

猫鼬文档声明您可以使用 parent.children.id(id);但我无法让它工作。

【问题讨论】:

    标签: node.js mongoose crud


    【解决方案1】:

    Usertask 字段包含作为嵌入式子文档的任务,而不是对另一个集合的引用,因此您无法独立于用户查询任务(就像您尝试做的那样)。

    要查询嵌入式任务子文档,您可以使用如下查询:

    User.findOne({'task._id': req.params.id})
      .select('task.$') // Just include the matching task element
      .exec(function(err, user) {
        if(!user) {
          res.statusCode = 404;
          return res.send({ error: 'Not found' });
        }
        if(!err) {
          // The matching task will always be in the first element of the task array
          return res.send({ status: 'OK', task: user.task[0] });
        } else {
          res.statusCode = 500;
          console.log('Internal error(%d): %s', res.statusCode, err.message);
          return res.send({ error: 'Server error' });
        }
      }
    );
    

    为了提高效率,您需要在{'task._id': 1} 上添加一个索引。

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 2016-08-27
      • 2015-03-29
      • 1970-01-01
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      相关资源
      最近更新 更多