我正在尝试使用架构创建新文档
const schema = new mongoose.Schema({
room: String,
messages: Array
})
const ConversationModel = mongoose.model('Conversation', schema)
const Conversation = new ConversationModel()
Conversation.findOneAndUpdate({room: data.room})
控制台输出:
UnhandledPromiseRejectionWarning: TypeError: Conversation.findOneAndUpdate is not a function
我可以创建它而无需使用这样的架构
db.collection('conversations').findOneAndUpdate(
{room: data.room},
{$addToSet: {messages: ''}},
{returnOriginal: false, upsert: true}
)
但是使用架构会导致此问题
答案 0 :(得分:0)
使用您的模型实例创建文档,即
const conversationSchema = new mongoose.Schema({ room: String, messages: Array })
const Conversation = mongoose.model('Conversation', conversationSchema)
const conversation = new Conversation({ room: data.room, messages: [''] })
conversation.save(err => {
if (err) return handleError(err)
// saved!
})
或使用create方法:
Conversation.create({ room: data.room, messages: [''] }, (err, conversation) => {
if (err) return handleError(err)
// saved!
});
或者,用于插入大批文档
Conversation.insertMany([{ room: data.room, messages: [''] }], err => {
});
或在模型上使用findOneAndUpdate
Conversation.findOneAndUpdate(
{ 'room': data.room, messages: [''] },
{ '$addToSet': { 'messages': ''} },
{ 'new': false, 'upsert': true }
(err, conversation) => {
if (err) return handleError(err)
// saved!
}
)