【问题标题】:How to create nested object in MongoDB schema如何在 MongoDB 模式中创建嵌套对象
【发布时间】:2017-01-06 22:49:32
【问题描述】:

我目前有一个用于保存用户数据的 MongoDB 文档的以下架构:

var userSchema =  new mongoose.Schema({
  username: {type: String, unique : true},
  password: {type: String},
  firstname: String,
  lastname: String,
  sketches: 
              [ 
                {name: String, 
                 sketch: Array}
              ]

草图属性需要是一个数组对象,其中每个对象关联一个草图的名称和一个保存草图数据的数组。由于某种原因,架构最终被创建如下:

{
    "__v" : 1,
    "_id" : ObjectId("57c4d7693aa85cea2acf4d4d"),
    "firstname" : "test",
    "lastname" : "name",
    "password" : "password123",
    "sketches" : [ 
        {
            "sketch" : []
        }
    ],
    "username" : "testname"
}

我不确定在 MongoDB 中创建嵌套对象的正确格式,但我假设它与 JSON 相同。应该如何构造模式以产生对象数组。

编辑:

从 PUT 请求中插入文档的网络服务:

app.route("/addSketch/:username").put(function(req, res, next) {
  var user_name = req.params.username;
  User.findOne({username:user_name},function(err,foundObject){
    if(err){
      console.log("error");
      res.status(500).send();
    }
    else{
      if(!foundObject){
        res.status(404).send();
      }
      else{
        
        if(req.body.strokes && req.body.sketchName){
          var sketchObj = [];
          sketchObj[req.body.sketchName] = req.body.strokes;
          foundObject.sketches.push(req.body.sketchData);
        }
        foundObject.save(function(err,updatedObject){
          if(err){
            console.log(err);
            res.status(500).send();
          }
          else{
            res.send(updatedObject);
          }
        });
      }
    }

  });


  console.log('saving on server');
   var form = formidable.IncomingForm();

   console.log(form);
   console.log('the type of the request received is', (typeof req));

  form.parse(req, function(err, fields, files) {
      res.writeHead(200, {"content-type": "text/plain"});
      res.write('received upload:\n\n');
    var name = fields.name;
    var newSketch = new SavedSketch();
      newSketch.name = name;
      newSketch.sketchData =  fields.value;
      newSketch.save(function(err,savedObject){
        if(err){
               console.log(err);
               res.status(500).json({status:'failure'})
            }
            else{
              console.log("ID: " + fields.value.id + " strokeData:" + fields.value.strokes);
               res.json({status: 'success'});
            } 
      });

         res.end();
  });
  });

【问题讨论】:

  • 你是如何在你的 Mongoose 代码中插入文档的,你能把那部分也显示出来吗?
  • @chridam 我刚刚更新了帖子。我也在考虑将草图数组作为用户文档的子文档,但我不确定最好的方式来做到这一点。

标签: mongoose database nosql


【解决方案1】:

架构

var userSchema =  new mongoose.Schema({
  username: {type: String, unique : true},
  password: {type: String},
  firstname:{type: String},
  lastname: {type: String},
  sketches: [
    {
      name: String,
      sketch : {type : Array}
    }
  ]
});

【讨论】:

  • 这似乎可行,我最终为草图创建了一个子文档。我将发布另一个答案。
【解决方案2】:

我最终为草图创建了一个子文档,并将其作为用户架构的子文档:

var sketchSchema =  mongoose.Schema({ name: String, sketchData : Array
  });
var SavedSketch = mongoose.model('Sketch', sketchSchema);
// });


var userSchema =  new mongoose.Schema({
  username: {type: String, unique : true},
  password: {type: String},
  firstname: String,
  lastname: String,

  sketches:[sketchSchema]


var User = mongoose.model('User', userSchema);

module.exports = User;

【讨论】:

  • 声明:password: {type: String} vs firstname: String 有什么区别?。
  • @Sunny {type : String} 等于 : String。第一种模式,我们可以添加更多选项,如password: {type: String, unique: true, requried: true }
猜你喜欢
  • 2018-05-20
  • 2021-06-21
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2021-06-09
  • 1970-01-01
相关资源
最近更新 更多