【发布时间】:2022-01-15 17:04:06
【问题描述】:
我正在使用mongoose 和express 分别创建我的数据库和服务器。
我的数据有如下架构:
const mongoose = require('mongoose')
const {Schema} = mongoose
const quotesSchema = new Schema({
tags: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tags' // I want to save an array of tags coming in from the request body
}
],
content: {
type: String,
required: true
},
author: {
type: String,
required: true
},
authorSlug: {
type: String,
},
dateAdded: {
type: Date,
default: Date.now()
},
dateModified: {
type: Date,
default: Date.now()
},
})
const Quotes = new mongoose.model('Quotes', quotesSchema)
module.exports = Quotes
我想保存来自请求正文的一组标签,但它只保存数组中的一项。
这是我的示例代码:
router.post('/', async (req, res, next) => {
try {
const {tags, author, content} = req.body
const slug = author.replace(/\s+/g, '-').toLowerCase()
var tagIds = []
tags.forEach( async (tag) => {
const foundTag = await Tag.find({name: tag}) // I first of all search my tag collection
// to see if the names supplied in the request body tags array exist,
// then try to extract their Objectids and store in an array to move to the next step - saving the quote
// foundTag.forEach(async (item) => {
// return await tagIds.push(item._id)
// })
for (var i = 0; i < foundTag.length; i++) {
tagIds.push[i]
}
console.log(tagIds)
const quote = new Quote({
tags: tagIds,
content,
author,
authorSlug: slug
})
const quoteToSave = await quote.save()
return res.status(201).json({
success: true,
msg: 'Quote Created Successfully',
quote: quoteToSave
})
})
} catch (error) {
console.error(error)
}
})
如何将完整的标签数组作为参数传递给要保存的报价。我认为这里的问题是它没有等待第二个标签进入数组。
这是我在 Postman 中的请求-响应图像:
如何从req.body 获取数组标签并将其保存为我的报价对象的一部分?目前,我正在我的forEach 循环中做所有事情,这对我来说似乎不够体面。有没有最好的方法,比如等待数据,然后保存部分不会有任何父控制语句,就像目前一样。
谢谢
【问题讨论】:
标签: node.js arrays express mongoose objectid