I have the following two schemas:
var UserSchema = new Schema({
provider: String,
username: String,
...
categories: [{type: Schema.Types.ObjectId, ref: 'Category'}],
...
});
export default mongoose.model('User', UserSchema);
and
var CategorySchema = new mongoose.Schema({
name: String,
description: String,
adultOnly: { type: Boolean, default: false },
...
});
export default mongoose.model('Category', CategorySchema);
Now whenever i create a new user, i want to autofill his categories with all existing categories. Dependig on his age he might not get assigned to the adultOnly categories.
How do i do that? I tried it like that:
var newUser = new User(req.body);
...
newUser.saveAsync()
.spread(function(user) {
Category.findAsync({}, '_id', function(err, categories) {
if (!err){
var size = categories.length;
for (var i = 0; i < size; i++) {
user.categories.push(categories[i]._id);
}
} else {throw err;}
});
...
})
.catch(validationError(res));
but that doesn't seem to work.
Hope you can help me.
See if this helps :
var newUser = new User(req.body);
...
newUser.saveAsync()
.spread(function(user) {
Category.find({}, {'_id': 1}, function(err, categories) {
if (!err){
/*var size = categories.length;
for (var i = 0; i < size; i++) {
user.categories.push(categories[i]._id);
}*/
user.categories = [];
user.categories = categories;
} else {throw err;}
});
...
})
.catch(validationError(res));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.