我有两个猫鼬模型。第一个是水果,另一个是人。水果模型遵循fruit schema。
const fruitSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
rating: {
type: Number,
min: 1,
max: 10
},
review: String
});
最初,人员模型遵循以下模式
const personSchema = new mongoose.Schema({
name: String,
age: Number,
});
然后我在Fruit模型中创建了一些文档并保存。
const mango = new Fruit({
name: "Mango",
rating: 7,
review: "Awesome fruit"
});
const grave = new Fruit({
name: "Grave",
rating: 9,
review: "Sour fruit"
});
const pineApple = new Fruit({
name: "Pine Apple",
rating: 7,
review: "Awesome fruit"
});
const orange = new Fruit({
name: "orange",
rating: 8,
review:"orange review"
});
之后,我创建了一个Person文档并保存它
const jhon = new Person({
name: "John",
age: 32
});
jhon.save();
接下来,我修改PersonSchema,如下所示
const personSchema = new mongoose.Schema({
name: String,
age: Number,
favouriteFruit:fruitSchema
});
现在我想把John和mango连接起来,所以我写了这段代码,但它不起作用。解决方案是什么?
Fruit.find({name: "Mango"}, function(err, mango){
if(err)
{
console.log(err);
}
else{
console.log(mango[0]);
Person.update({name: "John"},{favouriteFruit: mango[0]});
}
mongoose.connection.close();
});
按如下方式修改PersonSchema
:
const personSchema = new mongoose.Schema({
name: String,
age: Number,
favouriteFruit: {
type: mongoose.Schema.Types.ObjectId,
ref: "Fruit",
}
});