已解决:在另一个架构中使用架构不起作用。错误:CastError:Cast to [ObjectId] 的值失败

我想要实现的目标:在另一个(配方架构)中使用一个架构(成分架构)。我的目标是在 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)
});
moumeiyuan 回答:已解决:在另一个架构中使用架构不起作用。错误:CastError:Cast to [ObjectId] 的值失败

如果有人正在寻找答案,这就是我所做的。我创建了一个新的 seeds 文件夹,其中包含 2 个文件 index.js seeds.js

在我的 seeds.js 中,我添加了我的数据配方对象并将其导出,以便我可以在其他地方使用它。

module.exports = [
    {
        title: "Mushroom and courgette fritter burgers",imageUrl: "https://recipes.lidl.co.uk/var/site/storage/images/2/5/4/2/252452-2-eng-GB/Mushroom-and-courgette-fritter-burgers.jpg",calories: 250,duration: 30,ingredients: [
            {
                ingName: "mushrooms",ingQty: 200,ingQtyUnit: "grams",ingImageUrl:"https://snaped.fns.usda.gov/sites/default/files/styles/crop_ratio_7_5/public/seasonal-produce/2018-05/mushrooms.jpg?h=b754914e&itok=Kldbq8Du" 
            },{
                ingName: "zucchini",ingQty: 2,ingQtyUnit: "piece",ingImageUrl:"https://healme.in/wp-content/uploads/2021/06/zucchini-2-1200.jpg" 
            }
        ]
    },]

然后,在我的 index.js 来自种子文件夹

const mongoose = require('mongoose');
const Recipe = require('../models/recipe');
const Ingredient = require ('../models/ingredient')
const recipes = require('../seeds/seeds')

mongoose.connect('mongodb://localhost:27017/foodApp',{useNewUrlParser: true,useUnifiedTopology: true})
    .then(() => {
        console.log("Mongo Connection open from seeds")
    })
    .catch((error) => {
        console.log("No,Mongo -> Connection Error " + error)
    })

const seedDB = async () => {
    await Recipe.deleteMany({});
    let title;
    let imageUrl;
    let calories;
    let duration;
    let ingredients;
    for (let i = 0; i < recipes.length; i++) {
        title = recipes[i].title;
        imageUrl = recipes[i].imageUrl;
        calories = recipes[i].calories;
        duration = recipes[i].duration;
        ingredients = recipes[i].ingredients;
        for (let ing of ingredients) {
            ingredients = ing;
        }
    const newRecipe = new Recipe ({
        title: title,imageUrl: imageUrl,calories: calories,duration: duration,ingredients: new Ingredient({
            ingName: ingredients.ingName,ingQty: ingredients.ingQty,ingQtyUnit: ingredients.ingQtyUnit,ingImageUrl:ingredients.ingImageUrl,})
    })
        await newRecipe.save();
    }
}

seedDB();

配方架构:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const recipeSchema = new Schema({
    title: {
        type: String,required: true,},imageUrl: {
        type: String,required: true
    },calories: {
        type: Number,required: false,duration: {
        type: Number,min: 0,ingredients: {
        _id: {
          type:mongoose.Schema.Types.ObjectId,ref:"Ingredient"
        },ingName: String,ingQty: Number,ingQtyUnit: String,ingImageUrl: String,})

const Recipe = mongoose.model('Recipe',recipeSchema);

module.exports = Recipe;

成分架构:

const mongoose = require("mongoose");

const ingredientSchema = mongoose.Schema({
    ingName: {
        type: String,ingQty: {
        type: Number,ingQtyUnit: {
        type: String,ingImageUrl: {
        type: String,})

const Ingredient = mongoose.model('Ingredient',ingredientSchema);

module.exports = Ingredient;
本文链接:https://www.f2er.com/5866.html

大家都在问