Mongoose:findByIdAndUpdate方法不更新也不插入

问题描述 投票:0回答:1

findByIdAndUpdate方法应该更新或插入数据库中的对象,但它什么都不做。它也没有抛出错误信息或其他东西。

我也尝试将原始ObjectId作为_id字段,但也不起作用。

有没有人知道更新或将对象插入数据库缺少什么?

const schema = new Schema({
    _id: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
    }
}, { toJSON: { virtuals: true } });

const myJson = {
    "myobject": {
    "_id": 781586495786495,
    "name": "MyName"
  }
}
const MyModel = mongoose.model('MyModel', schema);
MyModel.findByIdAndUpdate(myJson.myobject._id, myJson.myobject, { upsert: true });
node.js mongoose mongoose-schema
1个回答
1
投票

我使用了你的代码,它实际上按预期工作。之所以没有返回任何错误,也没有做任何事情,可能是因为您在模型上执行操作时没有连接到数据库。

请考虑以下代码段,它对我有用。

mongoose.connect('mongodb://localhost:27017/testingcollection').then(() => {
   const schema = new mongoose.Schema({
      _id: {
            type: Number,
          required: true
      },
      name: {
          type: String,
          required: true
      }
   }, { toJSON: { virtuals: true } });

   const myJson = {
      "myobject": {
      "_id": 781586495786495,
      "name": "MyName"
    }
     };

   const MyModel = mongoose.model('MyModel', schema);
   MyModel.findByIdAndUpdate(myJson.myobject._id, myJson.myobject, { upsert: true }).then(obj => {
      mongoose.connection.close();
   });
});
© www.soinside.com 2019 - 2024. All rights reserved.