【发布时间】:2022-01-01 21:14:02
【问题描述】:
我有以下架构,并且我在 mongodb 中有一个故事的文档,这个故事没有关键“粉丝”的值,它是一个数组。 我想在这个数组中添加一个元素。但是,我尝试使用fans.push、fans.pop 或fans = [element],它不起作用。请帮助我了解这样做的最佳方法是什么。
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);
const story1 = new Story({
title: 'Casino Royale',
author: author._id // assign the _id from the person
});
const fan = new Person({
_id: new mongoose.Types.ObjectId(),
name:'Fan 001',
age:38
});
fan.save(function(err){
if (err) return handleError(err);
const story1=Story.findOne({title:'Casino Royale'});
story1.fans=[fan._id];
story1.save(function (err){
if (err) return handleError(err);
});
});
【问题讨论】:
-
您没有将 story1 保存在您编写新故事的 Casino Royale 中,因此当您执行 findOne 时它不应该返回任何内容,因为尚未保存任何内容,请尝试控制台记录该内容,然后执行保存没有什么不是函数xD