将对象推入mongoDB中的数组 [英] pushing an object to an array in mongoDB
问题描述
我正在尝试将对象发送到模型中的数组,但是每次执行此操作时,该数组仍然为空.
I'm trying to send an object to an array in my model, but every time I do, the array is still empty.
我将对象传递到后端,然后到达此处:
I pass the object to the backend and it arrives here:
var addFavoriteRecipe = function(req, res){
if(req.user){
console.log(req.body);
userModel.User.find({_id: req.user._id}, {$push :{favoriteRecipes: {name: req.body.alias, _id: req.body._id}}}, function(err){
if(err){
res.send(err);
}else{
res.send("success!");
}
});
}else{
var sendBackError = {err: true, message: "You are not logged in."}
res.send(sendBackError);
}
}
req.body
上的控制台日志显示了我传递回的所有数据,并包含了我要推送到数组中的两个字段.
The console log on req.body
shows all the data I passed back, and has the two fields I'm trying to push into the array.
这是我的模特:
var userSchema = mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
friendsList: {
type: Array,
},
favoriteRecipes: {
type: Array,
}
});
我一直在弄弄代码,但是我真的不知道该从哪里去.我想认为这是我模型中的东西,但我不确定.
I've toyed around with the code, but I really am lost as to where I should go from here. I want to think it's something on my model, but I'm not entirely sure.
推荐答案
您可以通过以下方式为对象数组定义模型:
You can define your model for an array of objects, either this way:
favoriteRecipes: [{
_id: ObjectId,
name: String
}]
或
favoriteRecipes: { type : Array , "default" : [] }
但是,问题似乎在这里:
but, The problem seems to be here:
userModel.User.find(
{_id: req.user._id},
{ $push : {favoriteRecipes: {name: req.body.alias, _id: req.body._id}}},
function(err){
if(err){
res.send(err);
}else{
res.send("success!");
}
});
您正在使用 find
,需要将其更改为 update
:
You are using find
you need to change it to update
:
userModel.User.update(
{_id: req.user._id},
{ $push : { favoriteRecipes: {name: req.body.alias, _id: req.body._id}}},
function(err){
if(err){
res.send(err);
}else{
res.send("success!");
}
});
这篇关于将对象推入mongoDB中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!