我的模型架构
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
},
tweets: []
});
这是我用来与mongo沟通的方法
module.exports.getUserByUsername = function(username, callback){
const query = {username: username}
User.findOne(query, callback);
}
module.exports.addTweet = function(newTweet, newUser, callback){
User.updateOne(newUser, {$push: newTweet}, (err, isUpdate) => {
if(err) throw err;
callback(null, isUpdate)
});
}
我使用NodeJS来编码我的后端,我已经注册了一个用户和一个登录,但是当我尝试用该用户发布一条推文时,我得到了一个错误,并且我从未使用过ID。
router.post('/post', passport.authenticate('jwt', {session:false}), (req, res, next) => {
let newTweet = new User({
tweets:{
title: req.body.title,
body: req.body.body
}
})
User.getUserByUsername(req.body.username, (err, usert) => {
if(err) throw err;
if(!usert){
return res.json({success: false, msg: 'User not found'});
}
User.addTweet(newTweet, usert, (err, isUpdate) =>{
if(err) throw err;
if(isUpdate){
return res.json({success: true, msg: "Tweet Post"});
}
});
});
});
错误
这是我使用PostMan的错误
/home/daniel/react/miapp/Back/node_modules/mongodb/lib/utils.js:132
throw err;
^
MongoError: The field '_id' must be an array but is of type objectId in document {_id: ObjectId('5b26b4e911c67c4cfa6917e4')}
at Function.MongoError.create (/home/daniel/react/miapp/Back/node_modules/mongodb-core/lib/error.js:45:10)
at toError (/home/daniel/react/miapp/Back/node_modules/mongodb/lib/utils.js:149:22)
at /home/daniel/react/miapp/Back/node_modules/mongodb/lib/collection.js:1035:39
at /home/daniel/react/miapp/Back/node_modules/mongodb-core/lib/connection/pool.js:541:18
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
答案 0 :(得分:1)
您的getUserByUsername()返回来自mongo集合的文档,如
{_id: Object("...."), .....}
如果您只是想要用户名,请将项目查询添加到您的getUserByUsername()中:
const project = {_id:0,username:1}
User.findOne(query, project,callback)
这只返回文档的用户名。
同时将新推文的定义更改为:
let newTweet = {tweets: {title: req.body.title,body: req.body.body}}
编辑:你还可以做的是像以前一样让你的getUserByUsername代码改为你的updateOne代码(如上所述定义newTweet):
User.updateOne({_id: newUser._id}, newTweet, callback)
理想情况下,您应该只在mongo集合中投影_id并在更新时对其进行查询,因为它不仅可以在退回不必要的数据时将您从网络中保存下来,而且由于编制索引,更新查询也很快。