我需要使用猫鼬将用户选择的类别(业务,技术,体育...)保存在具有类别数组的用户集中。
这是我的用户架构和分类数组,我要在其中保存用户类别。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = Schema({
nick:{
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
categories:[{
type: String
}]
});
module.exports = mongoose.model('User', UserSchema);
答案 0 :(得分:1)
更改
categories:[{
type: String
}]
收件人
categories:[
category: {
type: String
}]
答案 1 :(得分:0)
您可以尝试以下方法:
$ ansible-playbook playbook.yml -i hosts
PLAY [all] ***************************************************************************
TASK [ping] **************************************************************************
ok: [example]
PLAY RECAP ***************************************************************************
example : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
您可以定义类别类型数组并存储ID和字符串数组
答案 2 :(得分:0)
例如:
categories:[
{type: Schema.Types.ObjectId, ref: 'Categories'}
]
答案 3 :(得分:0)
您的架构对我来说还不错。您是在问如何通过定义的模式将数据实际插入类别吗?
此外,您可能想在类别数组架构中添加_id:false,否则猫鼬会自动为所有条目赋予_id。
var arr = [2, 5, 5.5, 3, 6.8, 0, -5];
function filtrate(el) {
return el > 0 && el % 1 == 0;
}
console.log(arr.filter(filtrate));
要将数据插入类别,您可以执行以下操作:
categories:[{
_id: false,
type: String
}]
当然,您不必为此使用async await,同样的事情也可以用于回调。
// Get a user for the example.
const user = await UserModel.findOne({});
// Add the business category to the set. If you just push, then you'll end up with duplicates. AddToSet adds them if they don't already exist. user.categories.addToSet('business');
await user.save();
答案 4 :(得分:0)
您可以通过多种方式实现
var Empty1 = new Schema({ any: [] });
var Empty2 = new Schema({ any: Array });
var Empty3 = new Schema({ any: [Schema.Types.Mixed] });
var Empty4 = new Schema({ any: [{}] });
为什么您不引用相同的官方文档。 mongoose