我有这样的架构:
<label>
我需要通过this.schema = new Schema({
userId: String,
userEmail: String,
preference: {
language: String,
enableEmailNotifications: Boolean
Schedule: {
EmailFrequency: String,
weekDay: String
}
},
environments: [
{
envId: String,
userPreference: {
language: String,
emailNotifications: Boolean,
Schedule: {
weekDay: String
timeOfTheDay: String
}
},
}
]
});
查找用户,然后从对象数组中按userEmail
查找environment
对象,并将新的envId
obj推入userPreference
数组
试过这个:
environments
但出现错误:var obj = {
$push: { preference }
}
const result = await preferencesModel.findOne({ userEmail, "environments.envId": { "$in": envId } }, obj, { upsert: true, new: true });
更新:
MongoError: Unsupported projection option: $push: { preference: ...
我要插入数组的对象:
const result = await preferencesModel.findOneAndUpdate({ userEmail, "environments.envId": envId }, obj, { upsert: true, new: true });
未插入所有属性,如下所示:
{
"envId": "u1",
"userEmail": "test@gmail.com",
"userPreference": {
"language": "en",
"timeZone": "gmt",
"enableEmailNotifications": true,
"summaryNotifications": true,
"summaryNotificationSchedule": {
"summaryEmailFrequency": "Weekly",
"weekDay": "Monday",
"timeOfTheDay": "32400"
}
}
}
"environments": [
{
"userPreference": {
"summaryNotificationSchedule": {
"timeOfTheDay": "32400",
"weekDay": "Monday"
},
"language": "en",
"timeZone": "gmt",
"summaryNotifications": true
},
"_id": {
"$oid": "5f5fcb23e8706e3f9c7ccdbc"
},
"envId": "u1"
},
{
"userPreference": {
"summaryNotificationSchedule": {
"timeOfTheDay": "32400"
}
},
"_id": {
"$oid": "5f5fcb72e8706e3f9c7ccdbf"
}
}
]
丢失
答案 0 :(得分:1)
您的查询需要以这种方式更新:-
var email = 'testemail@123.com';
var id = 'abc123';
var newPreference = {
//contains data according to your schema defination
}
console.log('Preference to be added :-\n', newPreference);
//check your preference which is getting pushed, it might not contain the complete data you seek.
var obj = {
$push: { environments: newPreference }
}
const result = await preferencesModel.findOneAndUpdate({
userEmail: email,
"environments.envId": id,
},
obj,
{
upsert: true,
new: true
});
您可以在findOneAndUpdate的第一个参数中匹配多个条件,因为第一个参数可以包含要施加在要获取的文档上的任意数量的条件。
也可以在数组内查找静态值,而无需使用$ in运算符。您可以简单地使用“。”就像我在上面的示例中向您展示的那样,在数组属性上单击(点)。
您可以在此处进行更多操作:https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/