【发布时间】: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