[英]How to push multiple objects in array using $push (Mongoose)
將多個對象推入數組時遇到很多麻煩。
我已經嘗試了此代碼的幾種不同變體,我要么最終將對象直接推送到數據庫,要么只推送數組的最后一個 object
這是我目前正在嘗試的代碼,它有效,但只推送最后一個 object (在本例中為星期三)。
collection.findOneAndUpdate(
{ name: 'yyy' },
{ $push: { schedule: monday, schedule: tuesday, schedule: wednesday}},
function (error, success) {
if (error) {
console.log("error");
console.log(error);
} else {
console.log("success");
console.log(success);
}
});
我試過了
collection.findOneAndUpdate(
{ name: 'yyy' },
{ $push: { schedule: monday, tuesday, wednesday}}
它只是將星期二和星期三推到了 main 中,而不是將它們放在 schedule 數組中。
這是我用於日程安排的架構
schedule: [
{
day: { type: String, default: ""},
closed: { type: Boolean, default: false },
start: { type: Number, default: 0},
startap: { type: String, default: "AM"},
end: { type: Number, default: 0},
endap: { type: String, default: "PM"}
}
]
我想推送到計划數組的日期變量的繼承人和示例
var monday = {
day:"Monday",
closed: false,
start:"700",
startap:"AM",
end:"1900",
endap:"PM"
};
顯然我可以只運行 7 次罰款和更新代碼,但我覺得有一種更有效的方法。
您可以使用$push
和$each
將Append 多個值添加到數組中。 例子:
collection.findOneAndUpdate(
{ name: 'yyy' },
{ $push: { schedule: {$each: [monday, tuesday, wednesday]}}}...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.