首先,我尝试了这个代码
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);
}
}
);
但我注意到,只有第一个朋友(即约翰尼约翰逊)得到保存和目标,以推动数组元素在现有的“朋友”数组似乎不工作,因为当我运行代码,在数据库中只显示“第一个朋友”和“朋友”数组只有一个元素!
所以简单的解决方案写在下面
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。
如果它不工作,使用下面的片段
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();