gpt4 book ai didi

javascript - NodeJs MongoDB 更新错误

转载 作者:行者123 更新时间:2023-12-03 01:39:50 24 4
gpt4 key购买 nike

我的模型架构

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: []
});

This are the methods i use to communicate with 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 有关的错误,并且我从不使用 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"});
}
});
});
});

The Error

这是我使用 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.

最佳答案

您的 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 并在更新时查询它,因为它不仅可以节省您从网络中检索不必要的数据的时间,而且由于索引,更新查询也很快。

关于javascript - NodeJs MongoDB 更新错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com