感谢您的帮助和宝贵的时间。正如您所建议的那样,我已经创建了如下的模式。现在我想根据客户名称获取记录,以计算他们在每个类别上花费的时间。请帮我解决这个问题。在此先感谢。
/ * 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:"nelson@gmail.com",
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)
})
答案 0 :(得分:1)
要创建子模式,您应首先定义它,然后插入主模式。或者,如果您预计会有很多时间表,那么引用独立模式可能更为可取。在这两种情况下,将这些附加到用户架构是有意义的:
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);