猫鼬中的嵌套模式

比乔伊·阿尔弗雷德(Bijoy Alfred)

感谢您的帮助和宝贵的时间。如您所建议,我已经创建了如下的架构。现在,我想获取基于客户名称的记录,以计算他们在每个类别上花费的时间。请帮我解决这个问题。提前致谢。

/ * var query = {'timesheets [0] .categories [0] .catname':“ Admin”} //我想获取所有类别为admin的记录或文档* /

    Timesheet = new Schema({
      created: {type: Date, default: Date.now},
      categories: [{
        catname: String,
        custname: String,
        hours: Number
      }]
    });

    User = new Schema({
      name: { type: String, required: true },
      email:String,
      password:String,   
      type:String,  
      timesheets: [Timesheet]
    });
    //timesheets: [{type: mongoose.Schema.Types.ObjectId, ref: 'Timesheet'}
    var User = mongoose.model("User",User);
    var Timesheet = mongoose.model("Timesheet",Timesheet);

    module.exports = function(app) {

        var timedata = {        
            created: new Date('2014-06-05'),
          categories:[{catname:"Admin",cusname:"Sony",hours:8}]           
      }

      var user = new User({
          name:"Nelson",
          email:"[email protected]",
          password:"welcome123",
          type:"Solutions"
          });

      var timesheet = new Timesheet(timedata);
            user.timesheets.push(timesheet);  

        user.save(function(err,user){ 
          console.log(user.timesheets.timesheet);     
        })
         //console.log('category name');
         //console.log(user.timesheets[0].categories[0].catname) 
        var query = {'timesheets[0].categories[0].catname':"Admin"}
        // I want to get 
         all the records or documents with category admin      

        User.find(query,function(err,catname){
            console.log('catname')
            console.log(catname)

        })
斯卡兹

要创建子模式,您应该首先定义它,然后将其插入主模式。另外,如果您预计会有很多时间表,则最好参考一个独立的架构。在这两种情况下,将它们附加到用户架构都是有意义的:

var Timesheet = new Schema({
  created: {type: Date, default: Date.now},
  categories: [{
    name: String,
    custname: String,
    hours: Number
  }]
});

使用嵌入式文档:

var User = new Schema({
  timesheets: [Timesheet]
});

然后可以使用以下命令直接进行插入:

// create new timesheet doc using your user doc
var timesheet = user.timesheets.create(myData);
user.timesheets.push(timesheet);

或简单地:

user.timesheets.push(data);

使用参考文件:

var User = new Schema({
  timesheets: [{type: Schema.Types.ObjectID, ref: 'Timesheet'}]
});

插入:

// push timesheet reference to your user doc
var timesheet = new Timesheet(data);
user.timesheets.push(timesheet._id);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章