[英]Push data to MongoDB with Mongoose
I try to build a favorite system on my website.我尝试在我的网站上构建一个最喜欢的系统。 When a user clicks a button, it select data and push it to the backend.
当用户单击一个按钮时,它会 select 数据并将其推送到后端。 This part is effective:
这部分是有效的:
const dataPush = {
idSave: idSaveAttr,
urlSave: urlSaveAttr,
imgSave: imgSave,
marqueSave: marqueSave,
smSave: smSave,
typeSave: typeSave,
precisionSave: precisionSave,
yearsSave: yearsSave,
coteEuSave: coteEuSave,
coteUsdSave: coteUsdSave,
coteGbSave: coteGbSave,
coteChfSave: coteChfSave
}
console.log(dataPush)
//push to backend
$.post('/fr/save', dataPush);
On the backend, I have a User model:在后端,我有一个用户 model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
//Create Schema
const User = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true,
required: true
}
favorites: {
type: [{
idSave: {
type: String
},
urlSave: {
type: String
},
imgSave: {
type: String
},
marqueSave: {
type: String
},
smSave: {
type: String
},
typeSave: {
type: String
},
precisionSave: {
type: String
},
yearsSave: {
trype: String
},
coteEuSave: {
type: String,
},
coteUsdSave: {
type: String,
},
coteGbSave: {
type: String,
},
coteChfSave: {
type: String,
}
}]
}
});
User.plugin(passportLocalMongoose);
mongoose.model('users', User);
But how to push all these elements to my Mongoose DB regarding my User model?但是,关于我的用户 model,如何将所有这些元素推送到我的 Mongoose 数据库? My favorite backend:
我最喜欢的后端:
//Load User Model
require('../../models/User');
const User = mongoose.model('users');
router.post('/save', ensureAuthenticated, (req, res) => {
const dataPush = req.body
console.log(dataPush)
})
router.get('/save', csrfProtection, (req, res) => {
res.send('yep')
})
And the output of the console.log:以及console.log的output:
[Object: null prototype] {
idSave: '10000',
urlSave: 'exmplae-of-so.com',
imgSave: 'https://example.com/models.jpg',
marqueSave: 'AC',
smSave: '10 HP',
typeSave: 'Cabriolet',
precisionSave: '',
yearsSave: '1913-1916',
coteEuSave: '28 035 €',
coteUsdSave: '$30,590',
coteGbSave: '£24,911',
coteChfSave: 'CHF 30’632'
}
I am not sure with your question but as per your comment i am suggesting, if favorite is new then add and if already available then update.我不确定您的问题,但根据您的评论,我建议,如果最喜欢的是新的,则添加,如果已经可用,则更新。
let userId = mongoose.Types.ObjectId("123");
let data = req.body;
if (!data.idSave) {
User.update(
{ _id: userId },
{
$push: {
"favorites.type": data
}
}
)
}
else {
User.update(
{
_id: userId, // optional
"favorites.type.idSave": data.idSave
},
{
$set: {
"favorites.type.$": data
}
}
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.