首页 > 解决方案 > 如何使用猫鼬和节点 js 在另一个模型中添加模型

问题描述

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

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 模型中。

标签: javascriptnode.jsmongodbmongoose

解决方案


您正在寻找人口

在 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
});

推荐阅读