【问题标题】:How to add a model inside another model with mongoose and node js如何使用猫鼬和节点 js 在另一个模型中添加模型
【发布时间】:2021-03-01 19:29:48
【问题描述】:

我正在做一个项目,并试图在另一个模型中添加一个模型,但我似乎不知道该怎么做。有什么建议吗? `

const userSchema = new mongoose.Schema({
    first_name: String,
    last_name: String,
    email: String,
    password: String,
});

const ItemSchema = new mongoose.Schema({
    date: String,
    loc: String,
    title: String,
   passage: String,
   file: String
});

const User = mongoose.model("User", userSchema);
const Item = mongoose.model("Item", ItemSchema);

const user1 = new User({
    first_name: "John",
    last_name: "arbuckle",
    email: "blablabal@asdf",
    password: "123456789"
});

const item1 = new Item({
    date: "Today",
    loc: "here",
    title: "message",
    passage: "This is an example",
    file: "none"
});

我想将此模型 const Item = mongoose.model("Item", ItemSchema); 添加到 User 模型中。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您正在寻找population

    在 userSchema 中添加items : { type: [Schema.Types.ObjectId], ref: 'Item' }

    const userSchema = new mongoose.Schema({
        first_name: String,
        last_name: String,
        email: String,
        password: String,
        items : {
             type: [Schema.Types.ObjectId],
             ref: 'Item'
        }
    });
    
    const ItemSchema = new mongoose.Schema({
        date: String,
        loc: String,
        title: String,
       passage: String,
       file: String
    });
    

    【讨论】:

    • 我没有看到 Item 模型进入 User 模型我看到它在外面但不是在里面。
    • 什么?没看懂
    • 我将尝试使用你提供的东西可能会奏效的另一件事。
    • 阅读人口文档。当您查询时,Mongo 将返回填充的用户文档。查询:User.find({first_name: "John"}).populate("items")
    • 哈不错 :) 恭喜!我访问了这两个网站,做得很好!
    猜你喜欢
    • 1970-01-01
    • 2021-05-24
    • 2014-01-31
    • 1970-01-01
    • 2015-06-20
    • 2019-07-01
    • 2019-11-20
    • 2018-10-13
    • 2021-08-17
    相关资源
    最近更新 更多