【问题标题】:Push a value to array in mongoose将值推送到猫鼬中的数组
【发布时间】:2019-03-22 14:14:10
【问题描述】:

我正在尝试向数组推送一个值但不起作用,我已经搜索并尝试了许多不同的解决方案 (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"
    }]
  });

【问题讨论】:

  • 问题解决了吗?
  • 不,我已经尝试过发布的两种解决方案,但我有同样的错误....我认为问题出在数组定义的创建用户中,但我不知道问题
  • 我终于找到了问题所在,我写的 auth 不是大写的...因为当调用 mongoose 方法时,我需要将它引用到架构,所以我的架构是 Auth 而不是 auth

标签: node.js mongodb express mongoose


【解决方案1】:

您正在尝试将对象推送到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){
//
});

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

【讨论】:

  • 你的架构定义有问题。
【解决方案2】:

尝试将架构更改为:

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]
});

【讨论】:

    【解决方案3】:

    最后我找到了问题,我写的 auth 不是大写的...因为当调用 mongoose 方法时,我需要将它引用到架构,所以我的架构是 Auth 不是 auth,谢谢大家:D

    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^/");
    }
     });
    });
    

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 2018-09-19
      • 2021-02-09
      • 1970-01-01
      • 2016-01-29
      • 2015-02-12
      • 2017-10-03
      • 1970-01-01
      • 2015-06-08
      相关资源
      最近更新 更多