【发布时间】:2015-12-25 18:24:18
【问题描述】:
所以我得到了两个猫鼬模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var eventSchema = new mongoose.Schema({
name: String,
date: String,
dogs: [{ type: Schema.Types.ObjectId, ref: 'Dog' }]
});
module.exports = mongoose.model('Event', eventSchema);
和
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dogSchema = new mongoose.Schema({
name: String,
age: String,
gender: String,
});
module.exports = mongoose.model('Dog', dogSchema);
Event 包含一个 dogs 数组,我试图弄清楚如何在这个数组中添加/删除狗。
在客户端我得到了这个方法:
$.ajax({
url: "http://localhost:3000/api/events/",
dataType: 'json',
type: 'POST', // Not sure if I should Post or Put...
data: {event_Id : this.props.choosenEvent._id, //Here I got the Id of the Event that i want to update by
dog_Id : this.props.events[dog]._id }, //adding this dog, which Id is here
success: function(data) {
}.bind(this),
});
},
在服务器 NodeJs 上,我获得了到 API 的路由。对我来说,使用 PUT 方法并首先获取正确的事件并将 event_Id 作为参数传递是有意义的。比如:
router.route('/events/:event_id')
.put(function(req, res) {
Event
.findById({ _id: req.param.event_id })
.populate('dogs')
});
但我停留在这一点上。任何帮助表示赞赏。谢谢!
更新!
谢谢!您的代码帮助很大,您使用 lodash .remove 从数组中删除了一条狗,是否有类似的方法可以使用 lodash 添加项目?
我给了 add 方法一个这样的例子:
router.route('/events')
.post(function(req, res) {
// Your data is inside req.body
Event
.findById({ _id: req.body.event_Id })
// execute the query
.exec(function(err, eventData) {
// Do some error handing
// Your dogs are inside eventData.dogs
eventData.dogs.push(req.body.dog_Id);
console.log(eventData)
});
// Update your eventDate here
Event.update({_id: req.body.event_id}, eventData)
.exec(function(err, update) {
// Do some error handing
// And send your response
});
});
当我点击console.log(eventData) 时,我可以看到dog_id 已按应有的方式添加到数组中。但是它不会保存到数据库中,并且错误表明eventData 未在Event.Update 中定义。我怀疑这是一个 Js-scope-issue。
让我感到困惑的是:
显然我希望能够在数组中添加和删除狗,并且
路线是这样的:router.route('/events')。
但是如果add-method和remove-method都在同一个路由上,那代码怎么知道我要去哪一个呢?
【问题讨论】:
标签: javascript ajax node.js mongoose reactjs