首页 > 解决方案 > 使用 findOneAndUpdate() 方法从 mongoose 模式中删除键值对

问题描述

以下是代码部分:

Profile 是一个 mongoose shcema 对象,包含多个键值对,代码的功能是使用 findOneAndUpdate 方法更新 Profile,将 profileFields 传递到$set其中包含新的键值对。

let profile = await Profile.findOne({ user: req.user.id });
            if (profile) {
                profile = await Profile.findOneAndUpdate(
                    { user: req.user.id },
                    { $set: profileFields },
                    { new: true }
                );
                console.log(profile);
                return res.json(profile);
            }

当键的值更改时,此代码可以正常工作。

例如。Profile.githubusername 是 abcd 并通过将 profileFields(其中 githubusername 为 xyz)传递$set给 findOneAndUpdate 方法进行更改。

但是当完全删除键值对时,代码会失败。

例如。profileFields 对象不包含 githubusername 键。在这种情况下,先前存储的 Profile.githubusername 值仍然存在。

但是我需要将配置文件的所有现有信息替换为 profileFields,这样如果 profileFields 中缺少键值对,它也会从配置文件中删除。

有没有办法做到这一点?

TIA

编辑:在调用 findOneAndUpdate() 之前,我添加了以下内容。但这仍然行不通。

let profile = await Profile.findOne({ user: req.user.id });
            // for (key in profile)
            //     console.log(key);
            for (key in profile) {
                if (Object.keys(profileFields).indexOf(key) === -1) {
                    console.log('missing key: 'key);
                    profileFields[key] = '';
                }
            }

当我 console.log(profile) 我得到:

{
   skills: [ 'HTML' ],
   _id: 60142f8f9a5bff1f08653478,
   user: 60142dc89a5bff1f08653477,
   company: 'Self Employed',
   bio: 'Useless international',
   status: 'Student or Learning',
   experience: [],
   education: [],
   date: 2021-01-29T15:53:51.693Z,
   __v: 10,
   location: 'Ahemdabad, Gujrat, India',       
   githubusername: 'k'
 }

据我了解技能,_id,用户,公司,生物... githubusername 是这个对象中唯一的键。

但是在运行for (key in profile)循环时,我还得到了很多其他键,其中一些是:

$__
isNew
errors
$locals
$op
_doc
$init
db
discriminators
schema
collection
$__originalValidate
$__save
$__validate
$__remove
$__deleteOne
$__init
$isMongooseModelPrototype
$__handleSave
save
$__delta
$__version
increment
$__where
remove
delete

如何仅循环通过用户定义的键?

标签: mongodbmongoosemongoose-schema

解决方案


你可以试试:

 delete mongooseObject["$init"] 

它将删除您的密钥,然后您可以操作其他密钥


推荐阅读