【问题标题】:Add an object to an array with mongoose使用 mongoose 将对象添加到数组中
【发布时间】:2019-02-13 19:16:59
【问题描述】:

我有一个允许文件上传的nodejs网络服务器,我想添加上传给用户的文件,但是每次我尝试添加到用户数据库数组时,它说它添加了它,但是当我读取用户文件时,它返回一个空数组。我使用以下代码尝试添加到数组中:

for (var x in files){
 User.findByIdAndUpdate(req.user._id,
  {$push: {"files":{name:files[x].filename}}},
  function (err, doc) {
   if (err) throw err;
   console.log(doc);
 });
}

使用的架构是这样的:

var schema = new mongoose.Schema({
 name: {type:String, required: true, trim: true, lowercase:true, unique: true},
 hash: {type:String, required: true },
 files: [],
 premium: {type:Boolean, default: false}
});

【问题讨论】:

    标签: arrays node.js mongodb mongoose schema


    【解决方案1】:

    删除 for 循环并使用 $each$push 运算符将多个值附加到数组字段,如下所示:

    User.findByIdAndUpdate(req.user._id,
        { '$push': {
            'files': {
                '$each': files.map(f => ({ name: f.filename }))
            }
        } },
        (err, doc) => {
            if (err) throw err;
            console.log(doc);
        }
    );
    

    您可能需要更新架构以明确定义文件数组字段:

    var schema = new mongoose.Schema({
       name: {type: String, required: true, trim: true, lowercase:true, unique: true},
       hash: {type: String, required: true },
       files: [{ name: String }],
       premium: {type: Boolean, default: false}
    });
    

    【讨论】:

    • 这似乎对我不起作用,因为 console.log(doc) 输出:{ premium: false, _id: xxxxxxxx, name: xxx, hash: xxxxxxxxxxxxx, files: [], __v: 0 }
    • @StephenToth files 数组的内容是什么,即 console.log(files)?
    • [ { fieldname: 'upload', originalname: '1533734295.png', encoding: '7bit', mimetype: 'image/png', 目的地: './uploads', 文件名: '90f0a33c739465bd .png',路径:'uploads/90f0a33c739465bd.png',大小:70933 } ]
    • 抱歉浪费您的时间,我从架构中删除 {name:String} 后它就开始工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2021-09-01
    • 2021-06-04
    • 2020-10-27
    • 2019-04-23
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多