首先我尝试了这段代码
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
但我注意到只有第一个朋友(即 Johhny Johnson)被保存,并且当我运行代码时,将数组元素推送到现有“朋友”数组中的目标似乎不起作用,在数据库中只显示“第一个朋友”和“朋友”数组只有一个元素!
所以简单的解决方法写在下面
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);
添加“{ upsert: true }”解决了我的问题,一旦保存代码并运行它,我看到“朋友”数组现在有 2 个元素!
upsert = true 选项会在对象不存在时创建它。默认设置为 false。
如果它不起作用,请使用以下 sn-p
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();