我正在尝试通过将帖子推送到我为其创建的数组中来更新我的 User 对象。我尝试了几种不同的方法,但到目前为止没有任何效果或更新用户对象。我是 MongoDB 的新手,但到目前为止我真的很喜欢它并且很高兴能更多地使用它。我到底做错了什么?
//Home page
router.get('/home', ensureAuthenticated, (req, res) => res.render('home', {user_mv: req.user}));
//Create topic page
router.get('/create-topic', ensureAuthenticated, (req, res) => res.render('create-topic', {user_mv: req.user}));
//Post handle
router.post('/create-topic', (req, res) => {
User.update( {_id: req.body.user_id},
{
$push: {
postArr: {
title: req.body.title,
category: req.body.category,
vista: req.body.vista,
description: req.body.description
}
}
});
res.send(req.body.user_id);
});
const DBmusevistaSchema = mongoose.Schema({
firstname: {
type: String,
required: false
},
lastname: {
type: String,
required: false
},
username: {
type: String,
required: false
},
email: {
type: String,
required: false
},
password: {
type: String,
required: false
},
date: {
type: Date,
default: Date.now
},
postArr: [
{
title: {
type: String,
required: false
},
category: {
type: String,
required: false
},
vista: {
type: String,
required: false
},
description: {
type: String,
required: false
}
}
]
});
<input type="hidden" class="form-control" name="user_id" value="<%= user_mv._id %>">
最佳答案
您的Update
语法没问题。
req.body.user_id
以字符串形式出现(假设您不使用任何特定的中间件来重新转换它)。
您所要做的就是 cast是 ObjectId
类型。像这样:
var ObjectID = require('mongodb').ObjectID
然后:
{_id: new ObjectId(req.body.user_id)}
编辑:
尝试等待 update
的 promise 返回,它应该仍然可以工作,无需等待,但没有看到整个代码,我无法确定。
这样做:
//Post handle
router.post('/create-topic', async (req, res) => {
let updateResult = await User.update( {_id: mongoose.Types.ObjectId(req.body.user_id)},
{
$push: {
postArr: {
title: req.body.title,
category: req.body.category,
vista: req.body.vista,
description: req.body.description
}
}
});
res.send(req.body.user_id);
});
此外,我发现您正在使用 mongoose,因此您可以使用以下命令来代替安装 Mongo 的 API:
var mongoose = require('mongoose')
然后:
{_id: new mongoose.Types.ObjectId(req.body.user_id)}
关于node.js - 如何按下 {key : value} object in my MongoDB array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812237/