如何解决猫鼬保存到数组
我有猫鼬问题。 我正在与用户一起创建食谱应用程序。 我能够创建用户,我能够使用户创建食谱。 我无法保存用户拥有的一组食谱和用户的收藏夹。
我该怎么做? 这是我的用户模型。
const mongoose = require("mongoose");
const Joi = require("@hapi/joi");
const jwt = require("jsonwebtoken");
const userSchema = new mongoose.Schema({
name: {
type: String,required: true,minlength: 2,maxlength: 255,},email: {
type: String,minlength: 6,unique: true,password: {
type: String,maxlength: 1024,admin: {
type: Boolean,createdAt: {
type: Date,default: Date.now,recipes: [{ type: mongoose.Schema.Types.ObjectId,ref: "Recipe" }],favorites: Array,});
userSchema.methods.generateAuthToken = function () {
const token = jwt.sign(
{ _id: this._id,admin: this.admin },process.env.JWT_TOKEN_KEY || "PrivateKey"
);
return token;
};
const User = mongoose.model("User",userSchema);
function validateUser(user) {
const schema = new Joi.object({
name: Joi.string().min(2).max(255).required(),email: Joi.string().min(6).max(255).required().email(),password: Joi.string().min(5).max(1024).required(),admin: Joi.boolean().required(),});
return schema.validate(user,{
abortEarly: false,});
}
function validateRecipes(data) {
const schema = new Joi.object({
recipe: Joi.array().min(1).required(),});
return schema.validate(data,});
}
function validateFavotrites(data) {
const schema = new Joi.object({
favorites: Joi.array().min(1).required(),});
return schema.validate(data,});
}
module.exports = {
User,validateUser,validateRecipes,validateFavotrites,};
这是我的食谱模型
const mongoose = require("mongoose");
const Joi = require("@hapi/joi");
const _ = require("lodash");
const recipeSchema = new mongoose.Schema({
title: {
type: String,minlength: 4,description: {
type: String,ingredients: {
type: String,directions: {
type: String,picture: {
type: String,minlength: 11,recipeNumber: {
type: String,minlength: 3,maxlength: 99999999999,user_id: {
type: mongoose.Schema.Types.ObjectId,ref: "User",});
const Recipe = mongoose.model("Recipe",recipeSchema);
function validateRecipe(recipe) {
const schema = Joi.object({
title: Joi.string().min(4).max(255).required(),description: Joi.string().min(4).max(255).required(),ingredients: Joi.string().min(4).max(255).required(),directions: Joi.string().min(4).max(1024).required(),picture: Joi.string().min(11).max(1024),});
return schema.validate(recipe,{ abortEarly: false });
}
async function generateRecipeNumber(Recipe) {
while (true) {
let randomNumber = _.random(100,999999);
let recipe = await Recipe.findOne({ recipeNumber: randomNumber });
if (!recipe) return String(randomNumber);
}
}
module.exports = {
Recipe,validateRecipe,generateRecipeNumber,};
我在那做错了吗?如果可以的话?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。