所以我有两个猫鼬的模型:保存对象到另一个模式阵列
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
数组和IM试图找出如何添加/删除狗给这个阵列。
在客户端上我得到了这个方法:
$.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。删除数组中的狗,是否有类似的方式来添加一个项目与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范围问题。
Onte事情是这样的:
很显然,我希望能够添加和删除阵列和 路线狗是这样的:router.route('/events')
。
但是,如果add-method和remove-method都在同一条路径上,那么代码如何知道我要去哪?
非常感谢!你把我放在正确的轨道上。如果可以,请查看更新。 – user2915962
@ user2915962我已经更新了我的答案。 –
非常感谢!这篇文章对我来说会派上用场。 – user2915962