在Node.js中将mongoose对象添加到数组,可以通过以下步骤实现:
npm install mongoose
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost/mydatabase';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(connectionString, options)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
const Schema = mongoose.Schema;
const mySchema = new Schema({
name: String,
age: Number,
});
const MyModel = mongoose.model('MyModel', mySchema);
const newObj = new MyModel({
name: 'John',
age: 25,
});
const myArray = [];
myArray.push(newObj);
这样,newObj
就会被添加到myArray
数组中。
完整的代码示例:
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost/mydatabase';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(connectionString, options)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
const Schema = mongoose.Schema;
const mySchema = new Schema({
name: String,
age: Number,
});
const MyModel = mongoose.model('MyModel', mySchema);
const newObj = new MyModel({
name: 'John',
age: 25,
});
const myArray = [];
myArray.push(newObj);
这样,你就可以将Mongoose对象添加到数组中了。请注意,以上代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改。
领取专属 10元无门槛券
手把手带您无忧上云