Javascript 通过Mongoose将对象推送到MongoDB子文档数组中
我目前已经建立了以下猫鼬模型:Javascript 通过Mongoose将对象推送到MongoDB子文档数组中,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我目前已经建立了以下猫鼬模型: var Customer = mongoose.model('Customer', { firstname : String, lastname : String, phone : String, street : String, city : String, state : String, zip : String, fixed : Boolean, readings: [Number] }
var Customer = mongoose.model('Customer', {
firstname : String,
lastname : String,
phone : String,
street : String,
city : String,
state : String,
zip : String,
fixed : Boolean,
readings: [Number]
});
其使用方式如下:
app.post('/api/findcustomer/:customer_id/:customer_reading', function(req, res) {
Customer.update({_id: req.params.customer_id},
{$push: {readings: req.params.customer_reading}},
{upsert:true},
function(err, customer){
if(err){
console.log(err);
}else{
console.log("Successfully added");
}
});
Customer.findOne({
_id : req.params.customer_id
}, function(err, customer) {
if (err)
res.send(err);
res.json(customer);
});
});
这是目前的工作。然而,我真正想做的是让读数(在我的模型中)成为一个由读数和日期组成的对象数组。我在这方面的最佳尝试包括以下更改:
readings: [{reading: Number, date: String}]
及
这对我不起作用,即使我在控制台中成功添加了日志,数组仍然为空。我不确定如何解决这个问题,我的搜索到目前为止还没有任何结果。在搜索时,我的相位可能是错误的,在这种情况下,我请求的读数是否被视为子文档数组或对象数组,或者仅仅是子文档本身
任何帮助都将不胜感激 Ug。。。看起来我的尝试是正确的,但是我试图向使用旧模式构建的客户添加读数。当我用新模式创建一个新客户并尝试将读取对象添加到数组中时,它成功了 使用GET方法调用更新违背了REST的约定。你应该使用PUT或者至少是POST。谢谢,是的,我在发布后发现了。它附带了一个以前函数的复制粘贴,我忘了更改。威尔:你能解释一下你是怎么用的吗?因为我也在尝试做同样的事情,这里是我发布的问题-。这里我有一个子数组,我在其中使用$push,但它不会产生任何结果。任何帮助都将不胜感激!
{$push: {readings: {reading: req.params.customer_reading, date: 'Some Date'}}}