node.js - 插入到 mongo 数组中没有发生?

标签 node.js mongodb mongoose mongodb-query

我是 MongoDb 的新手,我有一个关于数据插入的问题。我的“用户”集合的 Mongoose 模式:

var user = new mongoose.Schema({

  username : {type: String},
  email    : {type: String,index: {unique: true}},
  password : {type: String},
  feed     : [{
                title       : {type: String},
                description : {type: String},
                latitude    : {type:Number},
                longitude   : {type:Number},
                feedImages  : [{
                                imageUrl: {type: String}
                              }]
             }]
});

我想将数据插入到 feedimages 中,我的服务是:

app.post('/uploadFeedImage',function(req,res) {
    var _id         = req.body._id;
    var imageUrl    = req.body.imageUrl;
    db.user.update(
        {"feed._id":_id },
        {$push : {
            feedImages:{
                imageUrl:imageUrl
            }
        }
        },function (err,result) {
            if (err) {
                res.json({"success": '0', "message": "Error adding data"});
            }
            else {
                res.json({"success": '1', "message": "Data added"});
            }
        });
});

但是数据没有插入到表中,也没有报错,不知道是什么问题。

我的用户表如下所示:

TABLE

最佳答案

使用$压入数组的匹配元素。即 feed._id 匹配

试试这个:

db.user.update(
        {"feed._id":_id },
        {$push : {
            "feed.$.feedImages":{
                imageUrl:imageUrl
            }
        }
        },function (err,result) {
            if (err) {
                res.json({"success": '0', "message": "Error adding data"});
            }
            else {
                res.json({"success": '1', "message": "Data added"});
            }
        });

编辑

$更新位置运算符,它有助于仅更新符合更新条件的元素。欲了解更多信息,请参阅MongoDB $ operator Documentation.

关于node.js - 插入到 mongo 数组中没有发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39220550/

相关文章:

java - 如何使用 Java 运行 .group()

javascript - 我是否需要将 null 作为参数传递给 Javascript 函数/方法中的可选参数?

javascript - 使用通配符(如 'includes')从 module.exports 对象数组中检索值

node.js - 如何在node.js中隐藏 Mongoose 连接信息?

node.js - npm 安装时间失败,找不到 make 错误

javascript - 使用 Mongoose 和 Node/ express 保存新帖子时遇到问题

javascript - Mongoose 响应无法正确解析

使用 upsert 和多语法更新 Mongodb

mongodb - Mongoose 验证崩溃应用程序

javascript - 如何从 Controller 返回 PDF 文件