我正在尝试在mongo模型中的对象中推送数据 使用 req.params 方法 但是它给了我 ERROR:
MongoError:无法使用部分(friends.username的朋友)遍历元素({friends:[]})
这是我的代码:
BackEnd
router.post('/accept/:id/:username',isLoggedIn,function(req,res){
User.findOneAndUpdate({username:req.user.username,'friendRequest._id':req.params.id},
{$set:{'friendRequest.$.Status':'Friend','friendRequest.$.Color':'green'}},function(err,founduser){
if (err) {
throw err;
} else {
User.findOneAndUpdate({username:req.user.username},
{$push:{'friends.username':req.params.username}}
,function(err,founduser){
if (err) {
throw err;
} else {
//Error is coming from this line
User.findOneAndUpdate({username:req.params.username},
{$push:{'friends.username':req.user.username}}
,function(err,founduser){
if (err) {
throw err;
} else {
res.render("back");
}
})
}
})
}
})
})
**My Model**
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var UserSchema = new mongoose.Schema({
username:String,
password :String,
friends:[{
username: String //Here I wanna insert a data
}],
前端
<form action = "/accept/<%=request._id%>/<%=request.username%>" method = "post">
<button id="add" class="ui medium <%=request.Color%> button"><%=request.Status%></button>
</form>
答案 0 :(得分:0)
需要进行一些小改动:
User.findOneAndUpdate({
username: req.params.username
}, {
$push: {
"friends":{
username:req.params.username
}
}
},function(err,founduser){
if (err) {
throw err;
} else {
res.render("back");
}})