推入值以猫鼬数组

时间:2018-10-17 19:55:23

标签: node.js mongodb express mongoose

我正在尝试将值推入数组,但没有用,我进行了搜索,并尝试了许多不同的解决方案(Here)或Here,但是没有人总是返回:

POST /users/addfollower 500 2.353 ms - 1410

我的代码:

console.log("Id da aggiungere ai follower: " + req.body.idf);
console.log("Id utente:" + req.user._id);
auth.findAndUpdate({_id: req.user._id}, {$push: {'amici': {"user": req.body.idf}}}).exec(function(err,res){
//
});

我的模式:

const authschema = mongoose.Schema({
 _id: mongoose.Schema.Types.ObjectId,
 username: String,
 nome: String,
 cognome: String,
 email: String,
 password: String,
 cookie: String,
 pp: String,
 descrizione: String,
 autenticazione: Boolean,
 token: String,
 amici: [{
  user: String
 }]
});

创建用户:

  const auth = new Auth({
    _id : new mongoose.Types.ObjectId(),
    username: req.body.username,
    nome: req.body.nome,
    cognome: req.body.cognome,
    email: req.body.email,
    password: hash,
    pp: "/uploads/user.png",
    descrizione: "Aggiungi qui la tua descrizione",
    autenticazione: false,
    token: token,
    amici: [{
      user: "start"
    }]
  });

3 个答案:

答案 0 :(得分:0)

您正在尝试将对象推送到amici属性,但已将其定义为数组类型。

尝试更改

auth.findAndUpdate({_id: req.user._id}, {$push: {'amici': {"user": req.body.idf}}}).exec(function(err,res){
//
});

auth.findAndUpdate({_id: req.user._id}, {$push: {'amici': [{"user": req.body.idf}]}}).exec(function(err,res){
//
});

我不能保证这是唯一的问题,但这只是一个开始。

答案 1 :(得分:0)

尝试将架构更改为:

const amiciSchena = mongoose.Schema({
   name: String 
});  

const authschema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    username: String,
    nome: String,
    cognome: String,
    email: String,
    password: String,
    cookie: String,
    pp: String,
    descrizione: String,
    autenticazione: Boolean,
    token: String,
    amici: [amiciSchena]
});

答案 2 :(得分:0)

最后我发现了问题,我没有用大写写auth ...,因为当调用猫鼬方法时,我需要将其引用到架构,所以我的架构是Auth not auth谢谢所有:D < / p>

Auth.findByIdAndUpdate(req.user._id, {$push: {"amici": req.body.idf }}, {safe: true,   upsert: true}, function(err,doc){
if(err){
  console.log(err);
}else{
  console.log("Working \^0^/");
}
 });
});