-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmongoose-test.js
79 lines (71 loc) · 1.87 KB
/
mongoose-test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/clasedb')
var db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function () {
console.log('conexion realizada')
var userSchema = mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
min: 11,
max: 99
},
createdAt: {
type: Date,
default: Date.now
},
city: String
})
var groupSchema = mongoose.Schema({
name: {
type: String,
required: true
},
people: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
})
// groupSchema.methods.printPeople = function (g) {
// console.log(g.people.map(p => p.name))
// }
var User = mongoose.model('user', userSchema)
var Group = mongoose.model('group', groupSchema)
// ### con funcion callback ###
// User.find({}, function (err, users) {
// if (err) return handleError(err)
// console.log(users)
// })
// ### con promise ###
// let query = User.find({})
// query.select('name age')
// query.exec(function (err, users) {
// if (err) return handleError(err)
// console.log(users)
// })
// ### Find and update ###
// User.find({}, function (err, users) {
// if (err) console.log(err)
// users.forEach(user => {
// user.city = 'CDMX'
// user.save(function (err, updatedUser) {
// if (err) console.log(err)
// console.log(updatedUser)
// })
// })
// })
// ### find docs with subschema docs
Group.find({}, function (err, groups) {
if (err) console.log(err)
groups.forEach(group => {
console.log(group.name)
group.people.forEach(pId => {
User.findOne({_id: pId}, function (err, user) {
if (err) console.log(err)
console.log(user.name)
})
})
})
})
})