简体   繁体   中英

Can't pass values into MongoDB, using Node and Express, Mongoose

Whenever I try to pass in values all I get is this -

{ _id: new ObjectId("617794d97422073932859636"), __v: 0 }

Im using -

app.use(express.urlencoded());


app.use(express.json());

So not sure why its not decifering properly. Get requests seem to work, its just the put requests that aren't working properly.

    router.post("/", async (req,res) => {

  try {
    const result = await insertUser(req.body);
    console.log(result);

  }catch (error) {
    console.log(error)
    res.json({status: "error", message: error.message})
  }
  
  console.log(result)
    res.json({message: "new user created", result})
}); 

''

const insertUser = (userObj) => {
    return new Promise((resolve,reject) =>{
    UserSchema(userObj)
    .save()
    .then((data) => console.log(data))
    .catch((error) => console.log(error))

    })
}

module.exports = { insertUser,};

Any help would be appreciated! Thank you.

try this hope it will work

 module.exports.insertUser  = async (req, res, next) => {
       await YourModelShouldhere.create({
        whatever_your_key: req.body.your_input_data,
    })
    .then(result => {
        return res.status(200).json({
            message: "Created Successfully",
            statusCode: 200,
            data: result
        });
    })
    .catch(err => {
        return res.status(200).json({
            message: "Created Successfully",
            statusCode: 500,
            error: err
        });
    });
}

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