Mongo db $ push operator无法正常工作

时间:2017-11-14 11:46:44

标签: html json node.js mongodb mongoose

我正在尝试在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>

1 个答案:

答案 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");
                }})