[英]Push data to MongoDB with Mongoose
我嘗試在我的網站上構建一個最喜歡的系統。 當用戶單擊一個按鈕時,它會 select 數據並將其推送到后端。 這部分是有效的:
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);
在后端,我有一個用戶 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);
但是,關於我的用戶 model,如何將所有這些元素推送到我的 Mongoose 數據庫? 我最喜歡的后端:
//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')
})
以及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'
}
我不確定您的問題,但根據您的評論,我建議,如果最喜歡的是新的,則添加,如果已經可用,則更新。
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.