mongoose – 插入子文档

我有一个用户模型和一个日志模型。 日志模型是用户模型的子文档。 所以在我的用户模型中我有:

var mongoose = require('mongoose'); var Log = require('../models/log'); var UserSchema = new mongoose.Schema({ username: { type: String, unique: true }, logsHeld: [ Log ] }); 

然后在我的“日志”模型中,我有:

 var mongoose = require('mongoose'); var logSchema = new mongoose.Schema({ logComment: { type: String, }, }); module.exports = mongoose.model('Log', logSchema); 

所以创build“用户”时,“logsHeld”总是空白。 我想知道如何将子文档添加到此用户模型。

我试过做这个POST方法:

 router.post('/createNewLog', function(req, res) { var user = new User ({ logssHeld: [{ logComment: req.body.logComment }] }); user.save(function(err) { if(err) { req.flash('error', 'Log was not added due to error'); return res.redirect('/home'); } else { req.flash('success', 'Log was successfully added!'); return res.redirect('/home'); } }); }); 

但是这不起作用。 它还包括一个“新用户”行,我不认为我需要给予这将是一个现有的用户。

您需要使用logSchema而不是Log模型作为User模型中的子文档架构。 您可以按如下方式访问架构:

 var mongoose = require('mongoose'); /* access the Log schema via its Model.schema property */ var LogSchema = require('../models/log').schema; // <-- access the schema with this var UserSchema = new mongoose.Schema({ username: { type: String, unique: true }, logsHeld: [LogSchema] }); 

在另一个你正在面对另一个问题的答案中,从你的意见中提取

WriteError({“code”:11000,“index”:0,“errmsg”:“E11000重复键错误索引:testDB.users。$ email_1 dup键:

你得到这个,因为你的users集合中已经有一个文档,在email字段中最有可能是null值。 即使您的模式未明确指定email字段,您也可能在users.email上存在一个旧的未使用的唯一索引。

你可以用这个来确认

 testDB.users.getIndexes() 

如果是这种情况,并手动删除不需要的索引

 testDB.users.dropIndex(<index_name_as_specified_above>) 

并继续与邮政,看看是否已经纠正了错误,我打赌我的0.02美元,有一个旧的未使用的唯一索引在您的userscollections这是主要问题。

尝试使用logSchema引用子文档模式的logSchema, Log引用../models/log的全部内容

 var UserSchema = new mongoose.Schema({ username: { type: String, unique: true }, logsHeld: [ logSchema ] }); 

文档: http : //mongoosejs.com/docs/subdocs.html

尝试push插入项目在mongoosearrays

 var user = new User; user.logssHeld.push({ logComment: req.body.logComment }); user.save(function(err, doc) { //DO whatever you want }); 

看到这里的文档