猫鼬 - 如何将对象移动到另一个集合

时间:2017-10-13 08:33:58

标签: mongodb mongoose

我的数据库包括以下集合:

users
deleted_users

我的代码如下:

const name = { type: String, required: true, index: { unique: true } };
const UserSchema = new mongoose.Schema({ name });

const DeletedUserSchema = new mongoose.Schema({ name }, {
  versionKey: 'version',
});

const UserModel = mongoose.model('User', UserSchema);
const DeletedUserModel = mongoose.model('Deleted_user', DeletedUserSchema);

router.put('/:id/move', (req, res) => {
  UserModel.findOne(
    { _id: id }
  ).then((user) => {
    if (!user) {
      return fail(...);
    }
    console.log(`moving user width id ${id}`);
    const newUser = new DeletedUserModel(user);
    return newUser.save()
    .then(
      () => {
        console.log('ok');
      })
    .catch((err) => {
      console.log('catch err ', err);
    });
  });
}

但我总是收到

{ Error
    at model.wrappedPointCut [as save] (/~/prj/node_modules/mongoose/lib/services/model/applyHooks.js:111:29)
    at UserModel.findOne.then (/~/prj/src/routes/user/index.js:123:20)
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
  message: 'No matching document found for id "58dd804c434bdc1848d491cd"',
  name: 'VersionError' }

1 个答案:

答案 0 :(得分:0)

您是否可以检查您要查询的id不是String而是ObjectId,因为我认为您传递了String作为ID。