【发布时间】:2020-01-08 16:47:19
【问题描述】:
我想使用 mongodb 和 nodejs 将对象推送到数组中。 我的词架构是:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const wordSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
date: {
type: Date,
default: Date.now
},
ugrWordCyr: {
type: String,
required: true
},
ugrWordArb: {
type: String
},
rusTranslation: {
type: String,
required: true
},
examples: [
{
exCyr: { type: String },
trRus: { type: String },
exLat: { type: String },
trEng: { type: String },
exArab: { type: String }
}
],
origin: {
type: String
},
sphere: {
type: String
},
see: {
type: Boolean,
default: false
},
lexis: {
type: String
},
grammar: {
type: String
},
partOfSpeech: {
type: String
},
style: {
type: String
}
});
module.exports = Word = mongoose.model("words", wordSchema);
如您所见,架构中有示例数组。它需要充满动态创建的对象。所以用我的话 api 我正在做这件事,但它不起作用。
// @route POST api/words
// @desc Add words to profile
// @access Private
router.post(
'/',
passport.authenticate('jwt', { session: false }),
(req, res) => {
const { errors, isValid } = validateWordInput(req.body);
// Check validation
if (!isValid) {
// Return any errors
return res.status(400).json(errors);
}
Word.find({}).then(word => {
if (
word.filter(
wrd =>
wrd.ugrWordCyr.toString().toLowerCase() ===
req.body.ugrWordCyr.toLowerCase()
).length !== 0
) {
return res
.status(404)
.json({ wordalreadyexists: 'Word already exists' });
} else {
const newWord = new Word({
user: req.user.id,
ugrWordCyr: req.body.ugrWordCyr,
ugrWordArb: req.body.ugrWordArb,
rusTranslation: req.body.rusTranslation,
origin: req.body.origin,
sphere: req.body.sphere,
lexis: req.body.lexis,
grammar: req.body.grammar,
partOfSpeech: req.body.partOfSpeech,
style: req.body.style
});
// Social
newWord.examples = [];
/* if (req.body.exCyr) newWord.examples.exCyr = req.body.exCyr;
if (req.body.trRus) newWord.examples.trRus = req.body.trRus;
if (req.body.exLat) newWord.examples.exLat = req.body.exLat;
if (req.body.trEng) newWord.examples.trEng = req.body.trEng;
if (req.body.exArab) newWord.examples.exArab = req.body.exArab; */
newWord.examples.push({
exArab:req.body.exArab,
trRus:req.body.trRus,
exLat:req.body.exLat,
trEng:req.body.trEng,
exArab:req.body.exArab
})
newWord.save().then(word => {
//now update user model
User.findOne({ _id: req.user.id })
.then(foundUser => {
foundUser.score = foundUser.score + 150;
foundUser
.save()
.then(savedUser => {
res.json({ word, savedUser });
})
.catch(err => {
return res.status(400).json({ error: 'could not add score' });
});
})
.catch(err => {
return res.status(400).json({ error: 'could not find user' });
});
});
}
});
}
);
我做错了什么?前端没问题!
【问题讨论】:
-
您能否分享任何错误消息,或者究竟是什么不起作用?
-
没有特别的错误,当我检查我的 mongolab 云时,示例数组是空的。
-
Word.find({})返回什么? -
返回所有存在的单词。