简体   繁体   中英

mongoose, nodejs how to add items into mongo array

I have a collection like { id:"david123", friends[{id:joe321, lname"woo", fname"joe"}] }

i want to add new elements into friends

i currently have this, but it does not seem to be working

app.post('/users/:uid/friends', function(req, res){
  var userId = req.params.uid;
  Friend.update({'_id': userId},
    {$push: {Friends: req.body.friend}},
    { upsert : true },
    function(err, result){
      if (err){
    console.log(err);
  } else {
    res.status(200).json(result);
  }
  })
});

i defined my schema like this

var FriendSchema = new mongoose.Schema({
  _id: String,
  Friends: [{
    _id: String,
    fname: String,
    lname: String
  }]
});

when i make a request i send { friend: '{userId:"john123",lname"smoth",fname"john"}', userId: 'userId123' } and im getting [TypeError: Cannot use 'in' operator to search for '_id' in {userId:"john123",lname"smoth",fname"john"}]

The sentence "it does not seem to be working" tells us nothing, really. Is there any error printed? Is there bad data inserted? No data? What is the response to the HTTP request? Those are the most important questions but since no relevant info is provided I can only give you some hints:

  1. Make sure that the connection to Mongo is successful
  2. Make sure that you're connecting to the database that you think you are
  3. Make sure you use body parser with correct encoding if needed
  4. Make sure to use $addToSet instead of $push to avoid duplicates
  5. Make sure to return a response on error and not only on success
  6. Make sure you send a request with POST method with JSON content type
  7. Make sure that you send the data in the request body
  8. Make sure that the JSON in your request contains the friend property
  9. Make sure you have some request logging

For (3) see: https://github.com/expressjs/body-parser#bodyparserjsonoptions

For (4) see: https://docs.mongodb.com/manual/reference/operator/update/addToSet/

You didn't say anything about a framework that you use and you did not your question with a framework tag but your code suggests that you may be using Express. If that's the case then to use req.body in the request handlers you need to use a correct body parser middleware:

npm install body-parser --save

and in your code - at the beginning:

const bodyParser = require('body-parser');

and somewhere after you have app but before app.post(...); you need:

app.use(bodyParser.json());

if you want to have the request body parsed as JSON so you could use req.body and req.body.friend in your handler.

And use some basic logging in your request handler:

app.post('/users/:uid/friends', (req, res) => {
    // start with:
    console.log('Request body:' JSON.stringify(req.body));
    // the rest of the logic ...
});

to see what is actually passed in the response and that it is correctly deserialized by the appropriate body parser.

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