【发布时间】:2020-11-16 17:31:54
【问题描述】:
我尝试在我的网站上构建一个最喜欢的系统。当用户单击按钮时,它会选择数据并将其推送到后端。这部分有效:
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);
在后端,我有一个用户模型:
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);
但是如何将所有这些元素推送到我的 Mongoose DB 关于我的用户模型? 我最喜欢的后端:
//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的输出:
[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'
}
【问题讨论】:
-
看不懂
User Object ID -
是的,但是我怎样才能找回它(如果我有多个用户)?
-
我确保我的用户已通过身份验证,因此我不确定是否需要检索它。但是当我只使用
User.update({$push: {"favorites.type": req.body}})时,我的 MongoDB 数据库中没有我最喜欢的 -
也许我的错误是我的 MongoDB 数据库中还没有 idSave 如果这是第一个要添加的最爱?
-
请解释一下这个问题..
标签: javascript mongodb mongoose