我正在处理一个项目,并试图在另一个模型中添加一个模型,但我似乎无法弄清楚如何去做。有什么建议吗? `
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);
添加到用户模型。
答案 0 :(得分: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
});