我想要实现的目标:在另一个(配方架构)中使用一个架构(成分架构)。我的目标是在 Recipe Schema 中,我的成分关键是成为我的 Ingredient Schema 数组。不知道为什么它不起作用或我做错了什么。如果你们有任何想法,我将不胜感激。请看下面我的代码。谢谢!
当我调用seeds.js时出现错误:
Error: Recipe validation failed: ingredients.0: Cast to [ObjectId] failed for value "[{"ingName":"tomato","ingQty":2,"ingQtyUnit":"piece","ingImageUrl":"https://upload.wikimedia.org/wikipedia/commons/8/89/Tomato_je.jpg"},{"ingName":"onion","ingQty":1,"ingImageUrl":"https://www.seeds-gallery.shop/9430-large_default/onion-seeds-dutch-yellow.jpg"}]" (type string) at path "ingredients.0
'ingredients.0': CastError: Cast to [ObjectId] failed for value "[{"ingName":"tomato","ingImageUrl":"https://www.seeds-gallery.shop/9430-large_default/onion-seeds-dutch-yellow.jpg"}]" (type string) at path "ingredients.0"
stringValue: '"[{"ingName":"tomato","ingImageUrl":"https://upload.wikimedia.org/wikipedia/commons/8/89/Tomato_je.jpg"}]"',messageformat: undefined,kind: '[ObjectId]',value: '[{"ingName":"tomato","ingImageUrl":"https://upload.wikimedia.org/wikipedia/commons/8/89/Tomato_je.jpg"}]',path: 'ingredients.0',reason: [CastError],valueType: 'string'
}
},_message: 'Recipe validation failed'
我是如何尝试的:
配方模型
const mongoose = require("mongoose");
const recipeSchema = mongoose.Schema({
title: {
type: String,required: true,},imageUrl: {
type: String,required: true
},calories: {
type: Number,required: false,duration: {
type: Number,min: 0,ingredients:[{
type: mongoose.Schema.Types.ObjectId,ref: "Ingredient"
}]
})
const Recipe = mongoose.model('Recipe',recipeSchema);
module.exports = Recipe;
成分模型:
const mongoose = require("mongoose");
const ingredientSchema = mongoose.Schema({
_id: Schema.Types.ObjectId,ingName: {
type: String,ingQty: {
type: Number,ingQtyUnit: {
type: String,ingImageUrl: {
type: String,}
})
const Ingredient = mongoose.model('Ingredient',ingredientSchema);
module.exports = Ingredient;
seeds.js
const mongoose = require('mongoose');
const Recipe = require('./models/recipe');
mongoose.connect('mongodb://localhost:27017/foodApp',{useNewUrlParser: true,useUnifiedTopology: true})
.then(() => {
console.log("Mongo Connection open")
})
.catch((error) => {
console.log("No,Mongo -> Connection Error " + error)
})
const seedRecipes = [
{
title: "Spring vegetable pie",imageUrl: "https://recipes.lidl.co.uk/var/site/storage/images/1/9/4/3/243491-2-eng-GB/Spring-vegetable-pie.jpg",calories: 300,duration: 120,ingredients:[
{
ingName: "tomato",ingQty: 2,ingQtyUnit: "piece",ingImageUrl:"https://upload.wikimedia.org/wikipedia/commons/8/89/Tomato_je.jpg"
},{
ingName: "onion",ingQty: 1,ingImageUrl:"https://www.seeds-gallery.shop/9430-large_default/onion-seeds-dutch-yellow.jpg"
},]
},]
Recipe.insertMany(seedRecipes)
.then(response => {
console.log(response)
})
.catch( error => {
console.log(error)
});