NodeJS API调用中Array中的Push和Pull元素

Push and Pull elements in Array in NodeJS API call

本文关键字:Push Pull 元素 中的 Array API 调用 NodeJS      更新时间:2023-09-26

在我的应用程序中,我使用Mongoose创建模式。我有一个用户模式和一个Tickit模式。每次用户创建tickit时,我都希望将tickit的id添加到用户架构上的"tickit"数组中,如下所示。代码起到了一半的作用——当我创建一个tickit时,该id会转到用户tickit数组——但当我删除tickit时时,该id不会从数组中删除。

Ticket.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);

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

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);
        });
    });   
}

也许我做这件事的方式不对,但我已经尝试了几个小时,任何帮助都会非常好。

这看起来像是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
    });
  });
};

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