简体   繁体   中英

NodeJs MongoDB Update Error

My Model Schema

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)
  });
}

Im using NodeJS to code my backend, i already register a user and a login but when i try to post a tweet with that user i get an error realted with the _id and i never use the ids.

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

This is the error i get using 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.

Your getUserByUsername() returns a document fromthe mongo collection like

{_id: Object("...."), .....}

If you just want the username add a project query to your getUserByUsername() as:

const project = {_id:0,username:1}
User.findOne(query, project,callback)

This returns only the username of the document.

Also change the definition of new tweet to:

let newTweet = {tweets: {title: req.body.title,body: req.body.body}}

Edit: What you can also do is let your getUserByUsername code as before instead change your updateOne code(define newTweet as mentioned above):

User.updateOne({_id: newUser._id}, newTweet, callback)

Ideally, you should project only the _id from the mongo collection and query it while updating as it not only saves you from the network throughout of retreiving unnecessary data but the update query is also fast due to indexing.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM