在NodeJS API调用中推送和拉出Array中的元素

时间:2015-04-07 14:37:18

标签: javascript arrays node.js mongodb mongoose

在我的应用程序中,我使用Mongoose来创建模式。我有一个用户Schema和一个Tickit Schema。每次用户创建tickit我都想将tickit的id添加到' tickits'我的用户架构上的数组,如下所示。代码一半工作 - 当我创建一个tickit时,该id转到用户tickits数组 - 但是当我删除tickit时,该id不会从数组中删除。

Tickit.js

var mongoose    = require('mongoose');
var Schema      = mongoose.Schema;
var tickitSchema = new Schema({
    title: String,
    description: String,
    author : { type: Schema.Types.ObjectId, ref: 'User' },
    comments: [{body:"string", by: Schema.Types.ObjectId}]
});

module.exports = mongoose.model('Tickit', tickitSchema);

user.js的

var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');
var Schema   = mongoose.Schema;
var Tickit   = require('../models/Tickit');

var userSchema = new Schema({
    email        : String,
    password     : String,
    tickits      : [Tickit.tickitSchema]

});

userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.password);
};

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

我创建和删除刻度的功能如下:

exports.create = function(req, res) {
    var tickit    = new Tickit(req.body);
    var user      = req.user;
    tickit.author = user._id;
    user.update({tickits : {id : tickit._id}}, {$push: {tickits: { id: tickit._id}}},function (err) {
        if (err) 
            return res.send(err);
    }); 
    user.save();
    tickit.save(function(err, tickits) {
        if (err) {
          res.send(err);
        } else {
          res.json(tickits);
        }
    });
};

exports.destroy = function(req, res) {
    var tickit_id = req.params.tickit_id;
    req.user.update({tickits : {id : tickit_id}}, {$pull: {tickits: { id: tickit_id}}},function (err) {
        if (err) 
            return res.send(err);
    });
    req.user.save();

    Tickit.remove({_id : req.params.tickit_id}, function(err, tickit) {
        if (err)
            res.send(err);

        Tickit.find(function(err, tickits) {
            if (err)
                res.send(err)
            res.json(tickits);
        });
    });   
}

也许我以错误的方式解决这个问题,但我已经尝试了几个小时,任何帮助都会非常棒。

1 个答案:

答案 0 :(得分:1)

save的异步特性似乎是一个问题。此外,稍微清理了架构以帮助澄清。

var Schema = mongoose.Schema;
var tickitSchema = Schema({
  title: String,
  description: String,
  author : {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  comments: [{
    body: String,
    by: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    }
  }]
});

var userSchema = Schema({
  email: String,
  password: String,
  tickits: [{
    type: Schema.Types.ObjectId,
    ref: 'Tickit'
  }]
});

module.export.create = function createTickit(req, res) {
  var tickit = Tickit(req.body);
  tickit.author = req.user;
  // Save the ticket first to ensure it exists
  tickit.save(function (err, tickit) {
    if (err || tickit === null) { return res.send(err || new Error('Ticket was not saved but there was no error...odd')); }

    User.findByIdAndUpdate(req.user.id, {$push: {tickits: tickit}}, {new: true}, function (err, user) {
      if (err) { return res.send(err) };

      res.json(ticket); // or whatever else you want to send
    });
  });
};

module.export.destroy = function destroyTickit(req, res) {
  // Remove the ticket first to ensure it is removed
  Tickit.findByIdAndRemove(req.params.tickit_id, function (err, tickit) {
    if (err || tickit === null) { return res.send(err || new Error('Ticket was not removed but there was no error...odd')); }

    User.findByIdAndUpdate(req.user.id, {$pull: {tickits: tickit.id}}, {new: true}, function (err, user) {
      if (err) { return res.send(err) };

      res.json(ticket); // or whatever else you want to send
    });
  });
};

这将执行基本的创建/销毁但没有任何安全控制(确保谁有权销毁票证等)。

相关问题