保存mongoose模式而不创建新模式

时间:2018-03-19 09:56:30

标签: node.js express mongoose mongoose-schema

我正在使用以下代码,该代码也在使用

'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建议但现在我遇到了时间戳问题。即使我从架构中删除它。

1 个答案:

答案 0 :(得分:1)

您可以使用mongoose的findOneAndUpdate()upsert:true选项。

  

查找匹配的文档,根据更新arg对其进行更新,传递任何选项,并将找到的文档(如果有)返回给回调。

选项

  

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
  });

}