Recently,I got the problem when I tried to implement a comment function in an Android APP.
The definition of comments in user.js is as follow
comnents: [{
ownerID: {
type: String,
required: true,
},
commenterID: {
type: String,
required: true,
},
commenterName: String,
content: {
type: String,
require: true,
}
}],
And I have a request like that:
{
"_id":"60d204d6efc6c70022b08dc4",
"comments":[
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d205afefc6c70022b08dc8",
"commenterName":"Bob",
"content":"Hello World!"
},
{
"ownerID":"60d204d6efc6c70022b08dc4",
"commenterID":"60d20892efc6c70022b08dd2",
"commenterName":"Alice",
"content":"Hello Earth!"
}
]
}
Here is my API
router.post("/writecomment",jsonParser,
async(req,res,next)=>{
const errors=validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({erros:errors.array()});
}
User.findOneAndUpdate(
{ "_id": req.body._id},
{
$set: {
comments:req.body.comments
}
},
{overwrite:true},
function(err,resp){
if(err) throw err;
if(resp) {
return res.send({
msg:' change successfully'
});
}else{
return res.status(403).json({ success: false, message: 'Failed to change'});
}
}
)
}
)
How do I convert "comments" from request to comments array? Or have a better way to implement this function?
PS: I use Mongoose + Express Framework to develope.
const commentArray = [...req.body.comments]
Will make this for you:
[
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d205afefc6c70022b08dc8",
"commenterName": "Bob",
"content": "Hello World!"
},
{
"ownerID": "60d204d6efc6c70022b08dc4",
"commenterID": "60d20892efc6c70022b08dd2",
"commenterName": "Alice",
"content": "Hello Earth!"
}
]
Basically what is happening here is, we are iterating over the response you are getting and saving the result in an array. If you want to learn more about the ...
operator, check out this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.