【问题标题】:Saving mongoose schema without creating a new schema保存猫鼬模式而不创建新模式
【发布时间】:2018-08-27 20:12:09
【问题描述】:

我正在使用以下代码,它也可以工作

'use strict';

const Profile = require('../database/shemas/profileSchema');
const ProfileHelper = require('../helpers/profileHelper');
const logger = require('../utils/logger');

const createUpdateProfile = (req, res) => {
    //Fillout Schema
    let uuid = req.user.identities[0].id;
    let provider = req.user.identities[0].provider;
    let email = req.user.email;
    let firstName = req.user.name.split(' ').slice(0, -1).join(' ');
    let lastName = req.user.name.split(' ').slice(-1).join(' ');
    let pictureUrl = req.user.picture;
    let profileToSafe = new Profile({
        uuid,
        provider,
        email,
        firstName,
        lastName,
        pictureUrl
    });
    //createUpdate
    if (!!!uuid) {
        res.status(400).send('Invalid argument supplied');
    } else {
        Profile.findOne({ uuid }).then(object => {
            if (object !== null) {
                var upsertData = profileToSafe.toObject();
                delete upsertData._id;
                delete upsertData.uuid;
                delete upsertData.provider;
                Profile.update({ uuid }, upsertData, { upsert: true }, function (err, raw) {
                    if (err) {
                        console.log('callback -> err', err);
                    }
                    console.log('callback -> raw', raw);
                    res.status(200).send('Successful operation');
                });
            } else {
                profileToSafe.save();
                res.status(200).send('Successful operation');
            }
        })
    }
}

这是我的架构

'use strict';

// Mongoose schema definitions
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Profile Schema
const profileSchema = new Schema({
    uuid: {
        type: String,
        required: true,
        unique: true
    },
    provider: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    birthday: {
        type: String,
        default: ""
    },
    pictureUrl: {
        type: String,
        default: ""
    }, // Later we can add a default image for users who use cloud directory login
    onboardingDone: {
        type: Boolean,
        required: true,
        default: false
    }
}, {
        timestamps: true, // Add CreatedAt and updatedAt fields automatically
        strict: 'throw'
    });

const Profile = mongoose.model('Profile', profileSchema);

module.exports = Profile

但诀窍是,我需要删除 id

    delete upsertData._id;

一位同事坚持认为这是由于错误使用了

    let profileToSafe = new Profile({ ...

我尝试了不同的变体,但都没有奏效。真的有另一种(更)正确的方式来做我想做的事吗?

编辑:我按照@Sridhar 的建议做了,但现在我遇到了时间戳问题。即使我从架构中删除它。

【问题讨论】:

  • 为什么不直接使用 update 呢?你已经精确了upsert: true。不要使用findOne
  • @GrégoryNEUT 感谢您的提示。我本可以摆脱 fineOne() 但我仍然收到 ID 错误
  • 您正在通过uuid 值查询。如果配置文件存在,请使用附加值对其进行更新。如果没有,请创建一个新的配置文件。这就是你要在这里做的事情吗?
  • @Sridhar 正确:)

标签: node.js express mongoose mongoose-schema


【解决方案1】:

您可以使用猫鼬的findOneAndUpdate() 和upsert:true 选项。

找到一个匹配的文档,根据更新参数更新它,传递任何选项,并将找到的文档(如果有的话)返回给回调。

选项

upsert: bool - 如果对象不存在则创建它。默认为 false。

对您的代码进行这些更改

'use strict';

const Profile = require('../database/shemas/profileSchema');
const ProfileHelper = require('../helpers/profileHelper');
const logger = require('../utils/logger');

const createUpdateProfile = (req, res) => {

  const uuid = req.user.identities[0].id;
  const provider = req.user.identities[0].provider;

  const email = req.user.email;

  const firstName = req.user.name.split(' ').slice(0, -1).join(' ');
  const lastName = req.user.name.split(' ').slice(-1).join(' ');
  const pictureUrl = req.user.picture;

  if (!uuid) {
    return res.status(400).send('Invalid argument supplied');
  }

  Profile.findOneAndUpdate({
    uuid
  }, {
    provider,
    email,
    firstName,
    lastName,
    pictureUrl,
    $setOnInsert: {
      createdAt: Date.now()
    },
    updatedAt: Date.now()
  }, {
    upsert: true
  }).then(() => {
    res.status(200).send('Successful operation');
  }).catch((err) => {
    console.log('callback -> err', err);
    // You can send appropriate response here
  });

}

【讨论】:

  • 当你编辑他的代码时,请将不准确的let替换为const
  • 您也可以对 json 中的所有数据使用 shorthand 表示法
  • 谢谢!但是现在我的时间戳有问题。我在模式中定义了以下内容: { timestamps: true, // 自动添加 CreatedAt 和 updatedAt 字段 strict: 'throw' }
  • @GrégoryNEUT 感谢您的建议。更新了我的答案
  • @Sridhar 我添加了我的架构。似乎遇到了时间戳问题。即使我从架构中删除它,这也很奇怪。 TypeError:未定义类型undefinedtimestamps
猜你喜欢
  • 2012-04-22
  • 2014-12-04
  • 2017-06-12
  • 2016-11-18
  • 2015-03-25
  • 2016-08-05
  • 1970-01-01
  • 2012-02-02
相关资源
最近更新 更多