node.js - Mongoose 私有(private)集场

标签 node.js mongoose

假设我有这个架构:

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
});

mongoose.model('User', UserSchema);

我想避免有人意外地这样做:

const izzy = User.create({ name: 'Izzy', createdAt: "2000-01-28T01:04:30.809Z" });

我想确保忽略createdAt,因此如果这是一个正在创建的新对象(如我的示例代码),则将使用default值,但如果它是更新,则createdAt应保留其原始值。所以我想以某种方式配置 createdAt 使其不可以显式设置。

这可能吗?

最佳答案

通常当你想使用默认值时,你不会传递createdAt值。但是因为你说的是​​“意外”,所以你可以使用覆盖值传递。

User.create({ name: 'Izzy', createdAt: "2000-01-28T01:04:30.809Z" } , (err,user)=>{
    if(err){
     //handle
    }
    user.createdAt = Date.now;
    user.save();
});

关于node.js - Mongoose 私有(private)集场,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388845/

相关文章:

javascript - 使用 bcrypt-nodejs 时出现“没有给出回调函数”错误

node.js - 远程 Angular2 服务器在服务开发构建时挂起

node.js - Express JS、Mongoose JS 和 Jade 中的文本区域换行

javascript - Node.js/Express 和 Mongoose : Make an "observable" mongodb Connection with automatic pull on new Data?

node.js - 错误 : Virtual path "password" conflicts with a real path in the schema

javascript - 回调不是 mongoose.find({}) 中的函数

node.js - 使用 node-stream-zip 提取 zip 文件时读取错误的文件描述符

node.js - Sails.js - 对于 REST api 使用登录名而不是 ID

node.js - Mongoose:在 ReplicaSet 上阅读

node.js - 如何更新 Mongo 集合中的部分?